How do I get Kotlin classes instead of java classes

271 Views Asked by At

I'm trying to generate a subclass from an annotated class and getting methods parameters using code below, My problem is that I always get java types, not kotlin types which conflict with parent class causing override error, How do I get correct types kotlin or java types,this exactly happens with String,Int and List

 method.parameters.onEach { variableElement ->
                        if (!variableElement.asType().asTypeName()
                                .toString()
                                .contains("Continuation")
                        ) {
                            val types = ElementFilter.typesIn(variableElement.enclosedElements)
                            val parameterBuilder = ParameterSpec.builder(
                                variableElement.simpleName.toString(),
                                variableElement.asType().asTypeName()
                            )
                            function.addParameter(parameterBuilder.build())
                        }
                    }
2

There are 2 best solutions below

0
On

Since Kotlin types are just aliases for the underlying Java types you indeed won't get the correct type information without reading it from the @Metadata class annotation. Try the interop:kotlinx-metadata artifact that contains helpers for extracting this kind of information from the metadata.

2
On

KotlinPoet will output kotlin.String. Take a look at the kotlinpoet unit tests for a lot of examples, for example:

 @Test fun topLevelMembersRetainOrder() {
    val source = FileSpec.builder(tacosPackage, "Taco")
      .addFunction(FunSpec.builder("a").addModifiers(KModifier.PUBLIC).build())
      .addType(TypeSpec.classBuilder("B").build())
      .addProperty(
        PropertySpec.builder("c", String::class, KModifier.PUBLIC)
          .initializer("%S", "C")
          .build()
      )
      .addFunction(FunSpec.builder("d").build())
      .addType(TypeSpec.classBuilder("E").build())
      .addProperty(
        PropertySpec.builder("f", String::class, KModifier.PUBLIC)
          .initializer("%S", "F")
          .build()
      )
      .build()
    assertThat(source.toString()).isEqualTo(
      """
        |package com.squareup.tacos
        |
        |import kotlin.String
        |import kotlin.Unit
        |
        |public fun a(): Unit {
        |}
        |
        |public class B
        |
        |public val c: String = "C"
        |
        |public fun d(): Unit {
        |}
        |
        |public class E
        |
        |public val f: String = "F"
        |""".trimMargin()
    )

Taken from here:

https://github.com/square/kotlinpoet/blob/7c6f4dbc324fff1019d3e625f8a5dbace6c7905c/kotlinpoet/src/test/java/com/squareup/kotlinpoet/KotlinPoetTest.kt#L49