示例:
sealed interface Foo<out T> {
val value: T
}
data class Bar<out K: List<Int>>(override val value: K): Foo<K>
fun <T> processFoo(foo: Foo<T>) {
when (foo) {
is Bar -> foo.value.forEach(::println)
}
}
失败,出现以下错误:
未解析的引用.以下候选人均不适用 由于接收器类型不匹配:
kotlin.collections
中定义的public inline fun <T> Iterable<TypeVariable(T)>.forEach(action: (TypeVariable(T)) -> Unit): Unit
kotlin.collections
中定义的public inline fun <K, V> Map<out TypeVariable(K), TypeVariable(V)>.forEach(action: (Map.Entry<TypeVariable(K), TypeVariable(V)>) -> Unit): Unit
为什么这会失败呢?我认为,如果foo
是Bar
类型,那么我们就知道T
是List<Int>
的一个子类型.所以我们应该可以在上面拨打forEach
.我说错了吗?