kotlinpoet

How to initialize a variable and calling "apply { }" at the end in KotlinPoet


I'm trying to auto-generate classes were we create variables like this with KotlinPoet:

class test {
   var testObj: CustomObject = CustomObject().apply { custom = "custom" }
}

So far I've tried looking at the PropertySpec in KotlinPoet, but can't find any functions to generate variables while calling apply() at the end.

Is this even possible?


Solution

  • PropertySpec.Builder has an initializer() method that you should use in this scenario, however, there are no specialized API for generating initializers that include an apply block. See the CodeBlock documentation for more info on how to generate code for your initializer, plus there are many examples of generating similar constructs in KotlinPoet's unit tests that you can use for inspiration.