首页 > 解决方案 > 如何使用 FunSpec.overriding?在 Kotlin 诗人

问题描述

FleshgrinderGitHub 上提交。

该类FunSpec具有非常方便的覆盖方法,但是,尚不清楚在生成代码时如何使用它。

最小的例子:

FileSpec.builder("com.fleshgrinder", "KotlinPoet").apply {
    val className = ClassName("com.fleshgrinder", "KotlinPoet")
    addType(TypeSpec.classBuilder(className).apply {
        addFunction(FunSpec.builder("toString").apply {
            addModifiers(KModifier.OVERRIDE)
            addStatement("""return "KotlinPoet"""")
        }.build())
    }.build())
}.build().writeTo(System.out)

生成:

class KotlinPoet {
    override fun toString() = "KotlinPoet"
}

它生成的输出是完美的,但生成它的代码却不是。

FunSpec.overriding(Any::toString).apply {
    addStatement("""return "KotlinPoet"""")
}.build()

标签: kotlinkotlinpoet

解决方案


推荐阅读