我正在尝试在类内部生成对象定义。这是一个精简版本:
class SomeClass {
// need to figure out how to generate this
companion object {
// and this
object Constants {
val SOME_CONSTANT = "CONSTANT VALUE"
}
}
}
答案 0 :(得分:1)
您可以使用object
创建TypeSpec.objecBuilder
,然后使用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()