Search code examples
kotlinkotlinpoet

How to generate `by lazy` using KotlinPoet


I want to generate code like this:

class B private constructor() : A {

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

Using KotlinPoet:

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

How to generate by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED)? I can not find some useful APIs in document.


Solution

  • You're looking for the PropertySpec.Builder.delegate methods. You provide a CodeBlock representing the initializer that represents the delegate.

    Specifically for the code you want:

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