https://kotlinlang.org logo
r

rrva

06/05/2020, 11:48 AM
if I do a
when
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?
d

diesieben07

06/05/2020, 11:49 AM
It can if you use a sealed class.
m

Milan Hruban

06/05/2020, 11:51 AM
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()
    }
}
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,
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() // <--
}
Dumb example, but I hope you see my point. simple smile