小编TGI*_*GIO的帖子

Kotlin泛型超级/子类

尝试使用泛型类型类,但遇到以下问题,即:

类型不匹配:推断的类型是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
    }
}
Run Code Online (Sandbox Code Playgroud)

这是要点和科特林游乐场

所需的结果是函数 testType(superClass: SuperClass<SuperType>) 应在 不使用 …

generics kotlin

2
推荐指数
1
解决办法
1923
查看次数

标签 统计

generics ×1

kotlin ×1