kotlinkotlinpoet

How to implement Comparable in KotlinPoet?


Submitted by Fleshgrinder on GitHub.

How is it possible to implement Comparable for the class that is currently being generated?

There is the ParameterizedTypeName.get(Comparable::class, ?) method but it is unclear how the second parameter could be passed. The only thing available while generating a class is the ClassName of it.

Minimal example:

FileSpec.builder("com.fleshgrinder", "KotlinPoet").apply {
    val className = ClassName("com.fleshgrinder", "KotlinPoet")
    addType(TypeSpec.classBuilder(className).apply {
        addSuperinterface(ParameterizedTypeName.get(Comparable::class, Any::class))
    }.build())
}.build().writeTo(System.out)

Which generates:

package com.fleshgrinder

import kotlin.Any
import kotlin.Comparable

class KotlinPoet : Comparable<Any>

What I would like to have:

package com.fleshgrinder

class KotlinPoet : Comparable<KotlinPoet>

Solution

  • ClassName has the following extension method:

    fun ClassName.parameterizedBy(vararg typeArguments: TypeName)
    

    Here's how you can apply it to your use case:

    val className = ClassName("com.fleshgrinder", "KotlinPoet")
    val comparable = Comparable::class.asClassName().parameterizedBy(className)
    

    Please note that due to an IDE bug you'll need to manually add the following import:

    import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy