问题
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()
来源:https://stackoverflow.com/questions/50296204/how-to-use-funspec-overriding-in-kotlinpoet