gpt4 book ai didi

android - 如何从 KClass 反射进行 Kotlin 类型推断?

转载 作者:行者123 更新时间:2023-11-29 01:07:42 32 4
gpt4 key购买 nike

在下面的代码中,我无法正确安排输入/输出以使 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>)
}
}

最佳答案

我想您根本不需要in-KClasses 的投影:您的代码似乎没有传递StateHandler 或用 StateHandler 参数化到 KClass 的函数中。

如果变体的目的是您希望所有的 KClass 代表 StateHandler 的子类型,那么您可以使用 out -无处不在的投影:

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

关于android - 如何从 KClass 反射进行 Kotlin 类型推断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45697122/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com