Example:
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)
}
}
Fails with:
Unresolved reference. None of the following candidates is applicable
because of receiver type mismatch:
public inline fun <T> Iterable<TypeVariable(T)>.forEach(action: (TypeVariable(T)) -> Unit): Unitdefined inkotlin.collectionspublic inline fun <K, V> Map<out TypeVariable(K), TypeVariable(V)>.forEach(action: (Map.Entry<TypeVariable(K), TypeVariable(V)>) -> Unit): Unitdefined inkotlin.collections
Why this fails? I expect that if foo is of type Bar then we know that T is a subtype of List<Int>. So we should be able to call forEach on it. Am I wrong?
>Solution :
This problem is simply caused by a typo in your code.
If you replace is Bar with is Bar<*>, the compiler is able to infer that T is a List<Int> in that context and the code compiles.