以下代码应遍历所传递对象的类的父类(super class)链,直到到达顶层。
protected fun getBestMethodFor(o: Any): Method? {
val nodeClass = o.javaClass
val objectClass = Any::class.java
...
// Go through superclasses.
var c = nodeClass
while (c != objectClass && ans == null) {
debugMsg("Looking for class match for " + c.name)
...
c = c.superclass
}
...
}
这会导致 2 个错误:
Error:(57, 17) Kotlin: Type mismatch: inferred type is Class<in Any!>! but Class<Any> was expected
Error:(57, 19) Kotlin: Type inference failed. Expected type mismatch: inferred type is Class<in Any!>! but Class<Any> was expected
为什么会失败,我需要更改什么来解决这个问题?
注意:代码是使用 IntelliJ 的转换器自动从 Java 转换的。
最佳答案
在 Java 中, Class<T>.getSuperClass()
返回Class<? super T>
。 Kotlin 中的等价物是 Class<in T>
.
在您的代码中,var c = nodeClass
隐式类型为 Class<Any>
,与 Class<in T>
不兼容.
要解决此问题,只需直接指定类型 c:
var c: Class<in Any> = nodeClass
关于Kotlin:从类对象获取父类(super class) - 对象推断错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40329051/