How to use FunSpec.overriding? in KotlinPoet

夙愿已清 提交于 2021-02-11 13:34:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!