1

Submitted by Fleshgrinder on GitHub.

The FunSpec class has the very handy overriding method, however, it is unclear how this can be used while generating code.

Minimal example:

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)

Which generates:

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

The output it generates is perfect but the code to generate it is not.

FunSpec.overriding(Any::toString).apply {
    addStatement("""return "KotlinPoet"""")
}.build()
Egor
  • 39,695
  • 10
  • 113
  • 130

0 Answers0