Kotlin:从类对象获取超类 – 对象推理错误
下面的代码应该遍历传递对象的类的超类链,直到达到顶层。
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! but Class was expected Error:(57, 19) Kotlin: Type inference failed. Expected type mismatch: inferred type is Class! but Class was expected
为什么这是失败的,我需要改变以解决这个问题?
注意:代码是使用IntelliJ的转换器从Java自动转换而来的。
在Java中, Class
返回Class super T>
Class super T>
。 这个在Kotlin中的Class
是Class
。
在你的代码中, var c = nodeClass
有一个隐含types的Class
,它与Class
不兼容。
要解决这个问题,只需直接指定typesc:
var c: Class