2

I'm got a situation where I have a common property that must be defined on each of the subclasses of a sealed class. I'd like the ability to be able to access the set/list of these values without 'duplicating' the list (by hard coding it) Hopefully the below code conveys what I mean

    sealed class S {
        companion object {
            // want to avoid typing: listOf("these", "values", please")
            // instead grab it from the classes themselves
            val properties = S::class.sealedSubclasses.map { /* What to do here? */ }
        }

        abstract val property: String
    }

    class A(val d: String) : S() {
        override val property: String = "these"
    }
    class B(val e: String) : S() {
        override val property: String = "values"
    }
    class C(val f: String) : S() {
        override val property: String = "please"
    }

I'm aware of fun <T : Any> KClass<T>.createInstance(): T from kotlin.reflect.full, but my constructors have non optional parameters.

technoplato
  • 3,293
  • 21
  • 33
Morgan
  • 303
  • 2
  • 15

1 Answers1

0

You can create a createInstance(vararg) extension function for that:

fun <T : Any> KClass<T>.createInstance(vararg args: Any): T =
  java.constructors.first().newInstance(*args) as T

S::class.sealedSubclasses.map { it.createInstance("the string") }
CHAN
  • 1,518
  • 18
  • 16