Reputation: 1530
Using KotlinPoet, in order to generate a PropertySpec for adding properties to classes and constructors, you need a TypeName object.
The TypeMirror.asTypeName() KotlinPoet function is deprecated, because it won't always work correctly for Kotlin types.
But I can't find a single example of how to get a correct TypeName for a Kotlin class (e.g. kotlin.String) using the kotlinpoet-metadata APIs, the way the deprecation message says.
The docs for kotlinpoet-metadata APIs also seem completely broken (go to https://square.github.io/kotlinpoet/interop-kotlinx-metadata/#interop-with-kotlinx-metadata and click anything under the APIs section)
Does anyone have an example of how to replace TypeMirror.asTypeName() with some kotlinpoet-metadata code to get a TypeName, so that I can create a PropertySpec?
Upvotes: 8
Views: 1754
Reputation: 2365
I have found a way to get the TypeName
of a TypeElement
in my AbstractProcessor
, thanks to having access to its processingEnv
:
val kmClass = (typeElement.kotlinClassMetadata() as KotlinClassMetadata.Class).toKmClass()
val elementName: TypeName = ClassName(processingEnv.elementUtils.getPackageOf(typeElement).toString(), kmClass.name.substringAfterLast("/"))
It should also be doable without processingEnv
by splitting the kmClass.name
manually.
Upvotes: 0
Reputation: 2151
Not very sure if this aligns with the intention of the deprecation message, but this is what I got it to work.
I first had to add kotlinpoet-metadata-specs.
implementation("com.squareup:kotlinpoet:1.7.1")
implementation("com.squareup:kotlinpoet-metadata:1.7.1")
implementation("com.squareup:kotlinpoet-metadata-specs:1.7.1")
Then use a util method from com.squareup.kotlinpoet.metadata.specs.internal.ClassInspectorUtil
to create className.
val packageName = getPackage(element).qualifiedName.toString()
val typeMetadata = element.getAnnotation(Metadata::class.java)
val kmClass = typeMetadata.toImmutableKmClass()
val className = ClassInspectorUtil.createClassName(kmClass.name)
then use
val funSpec = FunSpec.builder("allNullableSet")
.receiver(className)
.returns(Boolean::class.java)
.addStatement(statement)
.build()
Upvotes: 3