Kotlinpoet 如何添加内部对象 class 定义?
Kotlinpoet How to add inner object class definition?
我正在尝试在 class 中生成一个对象定义。这是精简版:
class SomeClass {
// need to figure out how to generate this
companion object {
// and this
object Constants {
val SOME_CONSTANT = "CONSTANT VALUE"
}
}
}
您可以使用 TypeSpec.objecBuilder
创建 object
,然后将其嵌套在 class 和 addType
中,例如:
val constants = TypeSpec.objectBuilder("Constants")
.addProperty(PropertySpec.builder("SOME_CONSTANT", String::class)
.mutable(false)
.initializer("CONSTANT VALUE")
.build())
.build()
val someClass = TypeSpec.classBuilder("SomeClass")
.addType(constants)
.build()
我正在尝试在 class 中生成一个对象定义。这是精简版:
class SomeClass {
// need to figure out how to generate this
companion object {
// and this
object Constants {
val SOME_CONSTANT = "CONSTANT VALUE"
}
}
}
您可以使用 TypeSpec.objecBuilder
创建 object
,然后将其嵌套在 class 和 addType
中,例如:
val constants = TypeSpec.objectBuilder("Constants")
.addProperty(PropertySpec.builder("SOME_CONSTANT", String::class)
.mutable(false)
.initializer("CONSTANT VALUE")
.build())
.build()
val someClass = TypeSpec.classBuilder("SomeClass")
.addType(constants)
.build()