2

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"
      }
   }
}
ClayHerendeen
  • 187
  • 1
  • 4
  • 15
  • Change `object` to `companion object` – MFazio23 Sep 06 '18 at 20:01
  • I suppose it should be static and therefore inside the `companion object {}`, however, I still would still like to generate the `object Constants` block inside of the companion object. This allows for the namespacing of my constants. Will update code block to reflect this. – ClayHerendeen Sep 06 '18 at 20:09

1 Answers1

2

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()
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • Thank you, that was exactly what i was looking for. Wish some of these nuances were better documented in the kotlinpoet readme. Will most likely make a PR with this example – ClayHerendeen Sep 06 '18 at 20:38
  • 1
    Looks like it is actually already in the README, just doesnt have an output example. My bad, should have read more thoroughly. – ClayHerendeen Sep 06 '18 at 21:19
  • 2
    The unit tests are also a great place to look, that's where I found something similar to figure this one out. – zsmb13 Sep 07 '18 at 02:41