Search code examples
kotlinkotlinpoet

How should I add property within a function in kotlinpoet


I saw that TypeSpec.classBuilder has addProperty function which can generate below format of code

override val propertyName: PropertyType = PropertyValue

But when I tried to add the same property definition within one function of the class, there is no such addProperty for FunSpec.builder. How should I add properties within one function? Thanks.


Solution

  • You can't add properties inside a function directly, you can however add CodeBlock pieces:

    TypeSpec.classBuilder("Taco")
        .addFunction(FunSpec.builder("shell")
            .addCode(CodeBlock.of("%L", 
                PropertySpec.builder("taco1", String::class.asTypeName())
                    .initializer("%S", "Taco!").build()))
            .addCode(CodeBlock.of("%L",
                PropertySpec.builder("taco2", String::class.asTypeName().asNullable())
                    .initializer("null")
                    .build()))
            .addCode(CodeBlock.of("%L",
                PropertySpec.builder("taco3", String::class.asTypeName(), KModifier.LATEINIT)
                    .mutable(true)
                    .build()))
        .build())
    .build()
    

    This generates this code:

    import kotlin.String
    
    class Taco {
        fun shell() {
            val taco1: String = "Taco!"
            val taco2: String? = null
            lateinit var taco3: String
        }
    }
    

    (From this test of the library).