sealed class A
class B : A()
class C : A()
fun <T : A> f(a: T): T {
return when (a) {//Error: 'when' expression must be exhaustive, add necessary 'else' branch
is B -> a
is C -> a
}
}
a is of type T which is upper bounded by A, so a’s type should be subset of B and ‘C’, why the compiler still complains about exhaustiveness?
probably because of the same reason the following code doesn’t work:
class A
fun <T : A> f(foo : T){
val i = when(foo){
is A -> 1
}
}
thx @fatjoe79 for pointing out that my speculation below is not true.
My speculation:
Generics only exist at compile-time and not at runtime (at runtime they are replaced with Any?).
Probably the check if the when is exhaustive is done after the generics are replaced with Any??
Even stranger: if you add a third ‘is A -> a’ branch to the when, then the compiler recognises that that condition is always true, but still complains that it’s not exhaustive!