2

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.

Ellie Zou
  • 2,021
  • 2
  • 16
  • 21

1 Answers1

7

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())
Kiskae
  • 24,655
  • 2
  • 77
  • 74