嘗試使用泛型類,但得到了下面的問題,那就是:科特林泛型超/子類
類型不匹配:推斷類型是
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
所需結果LT是功能testType(superClass: SuperClass<SuperType>)
應該接受類ChildClass()
不使用通配符*
請在問題本身的代碼。 – nhaarman