如何使类型推理对遵循嵌套通用接口的实例起作用?

问题描述 投票:2回答:1

此最小示例

interface Foo<T> {
    fun foobinate(value: T)
}

interface Bar<T>

class AFoo<T> : Foo<T> {
    override fun foobinate(value: T) {}
}

class ABar<T> : Bar<T>

fun <T> doSomething(foo: Foo<Bar<T>>, x: Bar<T>) {
    foo.foobinate(x)
}

fun main() {
    val foo = AFoo<ABar<Int>>()
    doSomething(foo, ABar<Int>())
}

doSomething行出错:

Type mismatch: inferred type is AFoo<ABar<Int>> but Foo<Bar<Int>> was expected

有什么方法可以使它起作用,还是有一些概念上的东西阻碍着?

generics kotlin interface casting type-inference
1个回答
0
投票

声明像这样的doSomething应该起作用

fun <A : Bar<*>> doSomething(foo: Foo<A>, x: A) {
    foo.foobinate(x)
}
© www.soinside.com 2019 - 2024. All rights reserved.