0

I want to generate a kotlin class definition with typealias.

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

Any suggestions?

Sahka
  • 210
  • 3
  • 12

2 Answers2

1

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()
Saeed Entezari
  • 3,685
  • 2
  • 19
  • 40
  • nope, this will generate a typealias itself. But I need a class definition with typealias like: class TemplateState(var test: MyAlias) – Sahka Jan 27 '20 at 10:47
  • @Sahka I added the full implementation. I dont have an IDE so please excuse the typos. – Saeed Entezari Jan 27 '20 at 13:02
  • @NicoHaase yeah sure. – Saeed Entezari Jan 27 '20 at 13:14
  • @SaeedEntezari still nope... this is a result what your code produces package com.example import java.math.BigDecimal typealias MyAlias = BigDecimal class TemplateState( test: BigDecimal ) In short: typeAlias.type just returns original type... – Sahka Jan 27 '20 at 13:41
  • 1
    Can you check this one? @Sahka – Saeed Entezari Jan 27 '20 at 13:46
  • @SaeedEntezari Excellen!! It works! package com.example import MyAlias import java.math.BigDecimal typealias MyAlias = BigDecimal class TemplateState( test: MyAlias ) Thank, @SaeedEntezari! – Sahka Jan 27 '20 at 13:48
0

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.

Egor
  • 39,695
  • 10
  • 113
  • 130