I was wondering what was wrong with the following code:
sealed class Maybe<out T> {
class Some<out T>(val value: T) : Maybe<T>()
object None : Maybe<Nothing>()
fun or(f: () -> Maybe<T>): Maybe<T> = when (this) {
// error: ^
// Type parameter T is declared as 'out' but occurs in 'in' position in type () -> Maybe<T>
is Some<T> -> this
is None -> f()
}
}
T
is covariance (out) within Maybe
. Maybe<T>
is covariant within () -> Maybe<T>
(it’s the return type). So T
is should be covariant (out) within () -> Maybe<T>
, not contravariant (in) as the error says!
Or did I miss something?
If you want the intuition: I can get T
’s out of my Maybe. I can get Maybe<T>
's out of my function. Hence, I can never use that function to obtain something that is not a T
or a subclass thereof.
Current fix: use @UnsafeVariance