我想生成一个带有类型别名的 kotlin 类定义。
typealias MyAlias = BigDecimal
class TemplateState(var test: MyAlias) {
}
有什么建议吗?
您可以在文档中找到它:
//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
以确保生成的代码可编译。