如何从KClass反射Kotlin类型推断?

在下面的代码中,我无法正确地安排输入/输出,以至于()和()都按预期工作。 我已经尝试在属性和函数参数中切换进/出,但总是以不正确的输入错误结束。

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>) } } 

我想你根本不需要in KClass :你的代码似乎没有把StateHandler或者StateHandler参数化的东西传递给KClass的函数。

如果方差的意图是你希望所有的KClass es都代表StateHandler子类型,那么你可以在任何地方进行out -projections:

 class KStateMachine(private val states: List<StateHandler>) { private var currentState: KClass<out StateHandler> private val handlers: HashMap<KClass<out 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<out 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<out StateHandler>) } }