【发布时间】:2017-04-17 14:50:01
【问题描述】:
尝试使用泛型类但遇到以下问题,即:
类型不匹配:推断类型为
ChildClass,但应为SuperClass<SuperType>
open class SuperClass<T> where T: SuperType {
fun modifySomething(input: T): T {
input.someValue.inc()
return input
}
}
open class SuperType {
val someValue: Int = 0
}
class ChildClass : SuperClass<ChildType>()
class ChildType: SuperType() {
fun getModifiedValue(): Int {
return someValue
}
}
class TestEnvironment {
fun testType(superClass: SuperClass<SuperType>) {
// do something with superClass
}
fun itDoesntWork() {
testType(ChildClass()) // compilation error
}
}
这里是the gist 和the kotlin playground
期望的结果是函数 testType(superClass: SuperClass<SuperType>) 应该接受类 ChildClass() 不使用* 通配符
【问题讨论】:
-
请在问题中包含代码。