I want to generate a kotlin class definition with typealias.
typealias MyAlias = BigDecimal
class TemplateState(var test: MyAlias) {
}
Any suggestions?
I want to generate a kotlin class definition with typealias.
typealias MyAlias = BigDecimal
class TemplateState(var test: MyAlias) {
}
Any suggestions?
You can find it in the 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 doesn't really care whether a ClassName
represents a typealias
or a real type. In your case, ClassName("", "MyAlias")
(assuming MyAlias
is declared in the default package) is enough to use as the type of the constructor parameter. Of course you'd need to generate the typealias
separately to ensure the generated code compiles.