kotlinkotlinpoet

How to generate a class with a typealias parameter via kotlinpoet


I want to generate a kotlin class definition with typealias.

typealias MyAlias = BigDecimal
class TemplateState(var test: MyAlias) {
}

Any suggestions?


Solution

  • 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()