我想生成这样的代码:
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)?我在文档中找不到一些有用的API。
发布于 2018-07-02 08:44:37
您正在寻找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())https://stackoverflow.com/questions/51132110
复制相似问题