如何使用 KotlinPoet 生成 `by lazy`

How to generate `by lazy` using KotlinPoet

我想生成这样的代码:

class B private constructor() : A {

    companion object {
        val instance: B by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            B()
        }
    }
}

使用 KotlinPoet:

private fun genCompanionObject() = TypeSpec.companionObjectBuilder()
        .addProperty(PropertySpec.builder("instance", A::class.java).build()).build()

如何生成by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED)?我在 document.

中找不到一些有用的 API

您正在寻找 PropertySpec.Builder.delegate 方法。您提供一个 CodeBlock 表示代表委托的初始化程序。

专门针对您想要的代码:

.delegate(CodeBlock.builder()
    .beginControlFlow("lazy(mode = %T.SYNCHRONIZED)", LazyThreadSafetyMode::class.asTypeName())
    .add("B()") // Or however you want to implement this
    .endControlFlow()
    .build())