is there a way to enumerate all subclasses of a gi...
# announcements
k
is there a way to enumerate all subclasses of a given class and instantiate single instance of each? without going into too much metaprogramming etc...
n
well, even Kotlin doesn't really support metaprogramming. you'll need reflection though.
Class.newInstance()
, IIRC, is the Java way. must be something similar for Kotlin, or you can just do that
r
I’ve done this with sealed classes
You can iterate over sealedSubclasses or nestedClasses. If you have abstracts in the hierarchy, check and skip.
Then do something like
Copy code
private fun getInstance(commandClass: KClass<out ControllerCommand>): ControllerCommand {
    val objectInstance = commandClass.objectInstance
    if (objectInstance != null)
        return objectInstance
    val primaryConstructor = commandClass.primaryConstructor
    if (primaryConstructor != null)
        return primaryConstructor.call()
    throw IllegalStateException("$commandClass must be object or have primary constructor.")
}
k
Thanks, got it working! Combination of
sealedSubclasses
and
objectInstance
not super familiar with Kotlin/JVM, but this is all happening at runtime, so there's a slight performance penalty?
it's not some metaprogramming happening at compile time?
r
I believe it is using reflection (runtime).
k
👍
n
Kotlin supports some amount of reflection without the
kotlin-reflect
library, btw. and yeah, you'll want to cache these if you can.
352 Views