Search code examples
kotlincode-generationkotlinpoet

Kotlinpoet How to add inner object class definition?


I am trying to generate an object definition inside of a class. This is a distilled version:

class SomeClass {

   // need to figure out how to generate this
   companion object {

      // and this
      object Constants {
         val SOME_CONSTANT = "CONSTANT VALUE"
      }
   }
}

Solution

  • You can create the object with TypeSpec.objecBuilder and then nest it in a class with addType, for example:

    val constants = TypeSpec.objectBuilder("Constants")
            .addProperty(PropertySpec.builder("SOME_CONSTANT", String::class)
                    .mutable(false)
                    .initializer("CONSTANT VALUE")
                    .build())
            .build()
    
    val someClass = TypeSpec.classBuilder("SomeClass")
            .addType(constants)
            .build()