I asked this question here on Stack Overflow and didn’t get any answer.
Consider this setup:
open class Base
open class Derived: Base()
interface Foo<T: Base> {
fun produce(): T
fun consume(aT: T)
}
Following functions are valid:
fun apply1(f: Foo<*>) {
val p: Base = f.produce();
}
fun apply2(f: Foo<Derived>) {
val p: Base = f.produce();
}
but this one is not:
fun apply3(f: Foo<in Derived>) {
val p: Base = f.produce();
}
Type mismatch
Required: Base
Found: Any?
Generic type parameter T
has an upper bound. So it could be safely considered as a sub type of Base
as it is done in apply1
and apply2
. The question is why it is not valid to do the same when it is projected with in
?