【发布时间】:2020-01-27 10:33:20
【问题描述】:
我想用 typealias 生成一个 kotlin 类定义。
typealias MyAlias = BigDecimal
class TemplateState(var test: MyAlias) {
}
有什么建议吗?
【问题讨论】:
标签: kotlin kotlinpoet
我想用 typealias 生成一个 kotlin 类定义。
typealias MyAlias = BigDecimal
class TemplateState(var test: MyAlias) {
}
有什么建议吗?
【问题讨论】:
标签: kotlin kotlinpoet
你可以在documentation找到它:
//create a TypeAlias and store it to use the name later
val typeAlias = TypeAliasSpec.builder("MyAlias", BigDecimal::class).build()
val type = TypeSpec.classBuilder("TemplateState").primaryConstructor(
FunSpec.constructorBuilder().addParameter(
//You can use the ClassName class to get the typeAlias type
ParameterSpec.builder("test", ClassName("", typeAlias.name)).build()
)
).build()
FileSpec.builder("com.example", "HelloWorld")
.addTypeAlias(typeAlias)
.addType(type)
.build()
【讨论】:
KotlinPoet 并不真正关心 ClassName 是代表 typealias 还是真实类型。在您的情况下,ClassName("", "MyAlias")(假设 MyAlias 在默认包中声明)足以用作构造函数参数的类型。当然,您需要单独生成typealias,以确保生成的代码能够编译。
【讨论】: