如何初始化变量并在最后调用 "apply { }"

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

我正在尝试自动生成 类 我们用 KotlinPoet 创建了这样的变量:

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

到目前为止,我已经尝试查看 KotlinPoet 中的 PropertySpec,但在最后调用 apply() 时找不到任何生成变量的函数。

这可能吗?

PropertySpec.Builder 有一个 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 可以用来激发灵感。