over a type system, like
when {
foo is A ->
foo is B ->
}
why can the compiler not figure out compile-time if the when is exhaustive without an else branch?
Because you cannot know about all subclasses unless it's a sealed class. Someone can take your module as a dependency, and inherit given class.
s
sindrenm
06/05/2020, 12:24 PM
You should do a
when (foo)
instead:
Copy code
sealed class Foo
object A : Foo()
object B : Foo()
fun main() {
val foo: Foo = A
// This won't work, as there are other
// potential cases that doesn't involve
// `foo`.
// val bar = when {
// foo is A -> TODO()
// foo is B -> TODO()
// }
val bar = when (foo) {
is A -> TODO()
is B -> TODO()
}
}
sindrenm
06/05/2020, 12:25 PM
That is, your
when
, even if
foo
is an instance of a sealed class that only has an
A
and
B
subclass, isn't exhaustive,
sindrenm
06/05/2020, 12:26 PM
Meaning, not every case of your
when
is covered. Another potential case of your
when
could be this, for instance:
Copy code
when {
foo is A -> TODO()
foo is B -> TODO()
0 == 0 -> TODO() // <--
}
sindrenm
06/05/2020, 12:27 PM
Dumb example, but I hope you see my point. simple smile