在下面的代码中,我无法正确排列输入/输出,使得from()和to()都按预期工作。我尝试在属性和函数参数中切换输入/输出,但总是输入错误。
class KStateMachine(private val states: List<StateHandler>) {
var currentState: KClass<out StateHandler>
private set
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 goto(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")
}
}
inline fun <reified T: StateHandler> goto() {
goto(T::class)
}
abstract class StateHandler {
abstract fun from(fromState: KClass<in StateHandler>)
}
}
答案 0 :(得分:1)
我认为您in
es根本不需要KClass
- 投影:您的代码似乎没有通过StateHandler
或{{1}参数化的内容 in 到StateHandler
的函数。
如果方差的意图是您希望所有KClass
es代表KClass
的子类型,那么您可以使用StateHandler
- 在任何地方进行投影:
out