vendredi 14 décembre 2018

Kotlin - Extract underlying Class Type

So, I've been banging around in Kotlin reflection, and I can't seem to do the following:

object ThreadState {

    sealed class State {
object DANCE : State() {val validEvents: List<ThreadEvent> = listOf(ThreadEvent.Weave, ThreadEvent.Bob)}
object DUCK : State() {val validEvents: List<ThreadEvent> = listOf(ThreadEvent.Weave, ThreadEvent.Bob)}
object DODGE : State() {val validEvents: List<ThreadEvent> = listOf(ThreadEvent.Weave, ThreadEvent.Bob)}
.... Code
    }

.... Code
}

What I want to do is something like this:

val map = ThreadState.State::class.sealedSubclasses.map{ it to it.simpleName}.toMap()

map[ThreadState.State.DODGE]

And have it spit out the simple name of the class (in this case, DODGE).

The reason is because I can then simply reverse the map and get a value out from a name. I.e. ThreadState.fromString("DODGE") // ThreadState.State.DODGE

However, when I use ::sealedSubclasses, it gives a list of <KClass <out ThreadState.State>>

This is no bueno, because I cannot for the life of me find a way to get the ThreadState.State back out of any given element in the list of KClasses. I tried to run it as ThreadState.State but it told me that KClass can't be cast to ThreadState.State.

Any help would be massively appreciated.

In short - have a list of sealed classes that are singleton objects holding values. Need to make a map of the classes that conforms to <ThreadState, String>, where ThreadState is an instance of ThreadState.State and the string is just the simple name of the class.

I am really open to solutions - certainly doesn't have to be reflection, generics also welcome.





Aucun commentaire:

Enregistrer un commentaire