mardi 15 août 2017

How to do Kotlin type inference from KClass reflection?

In the code below, I'm having trouble arranging the in/out correctly such that both from() and to() work as expected. I've tried switching in/out in both properties and function parameters, but always end up with incorrect typing errors.

class KStateMachine(private val states: List<StateHandler>) {

private var currentState: KClass<out StateHandler>
private val handlers:HashMap<KClass<in StateHandler>, Int> = HashMap()

init {
    currentState = states[0]::class

    for (i in 0..states.size - 1) {
        handlers.put(states[i]::class, i)
    }
}

fun to(toState: KClass<in StateHandler>) {
    var index = handlers.get(toState)
    if (index != null) {
        var oldState = currentState
        currentState = toState
        states.get(index).from(oldState)
    } else {
        throw RuntimeException("to state unknown")
    }
}

abstract class StateHandler {
    abstract fun from(fromState: KClass<in StateHandler>)
}
}





Aucun commentaire:

Enregistrer un commentaire