kotlinpoet

Creating a static extension property for Kotlin with KotlinPoet


I am a complete newbie to using KotlinPoet.

I would like to programmatically generate the following code using KotlinPoet:

public val MyClass.Companion.classID: Long
  get() = 0x100

Unfortunately, after many attempts, I have not yet found a way to create that Companion Object of a class.

Maybe someone knows a possible solution, or can this not be realized with KotlinPoet?


Solution

  • Companion is simply a nested class, so you can create a ClassName representing the companion using ClassName.nestedClass():

    val myClass = ClassName(packageName = "", "MyClass")
    val companion = myClass.nestedClass("Companion")
    println(companion) // MyClass.Companion