1

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?

user12124207
  • 33
  • 1
  • 4

2 Answers2

1

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.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • Can you please write the code that would generate the code in question? I have a similar issue but with a multiline `apply` block. Unit tests are poor why of documenting features (hard to search, hard to see results). – Emperor Orionii Nov 12 '20 at 07:43
1

CodeBlock has a beginControlFlow method where you can define apply method using the following code. beginControlFlow method will deal with indentation and curly brackets.

beginControlFlow("${variableName}.apply")
//... do sth here
endControlFlow