0

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.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
Jiachuan Li
  • 195
  • 9

1 Answers1

2

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).

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • My I know what does %L and %S mean? – Jiachuan Li Apr 28 '18 at 15:12
  • You can find the documentation about these placeholders [here](https://github.com/square/kotlinpoet/blob/1262b3a512c276fb2ffee39a7830c1307440df4b/src/main/java/com/squareup/kotlinpoet/CodeBlock.kt#L30). – zsmb13 Apr 28 '18 at 15:37
  • @JiachuanLi, Would be great if you could accept this answer - seems like it helped you solve your problem – Egor Jun 01 '18 at 20:25
  • sorry I forgot to accept the answer, now this was accepted as the answer. Thanks for the help. – Jiachuan Li Jun 03 '18 at 13:48