Does Kotlin compiler verify that match block is exhaustive as in Scala?

Hello,

last time I checked this out in Kotlin it was not the case as far as a I remember. Now I work on a Scala project (I like Kotlin much as well, but it happens to be a Scala project) where we make use of Scala match blocks where the Scala compiler can verify that the match block covers all possible cases. For this particular type of application this is very valuable, because a missing case in a match block may result in true accidents, and I’m therefore really glad that Scala has this.

My question is whether Kotlin has this (meanwhile) as well. If not I really suggest to put it in. The load on the compiler to verify that all leaves of the match block are covered seems not to be that high.

Here is an example to explain what I mean:

val foo: Optional<Boolean>
val bar: Optional<Boolean>

(foo, bar) match {
      case (None, None) => Some(UNKNOWN)
      case (Some(true), Some(true)) => None
      case (Some(false), Some(true)) => None
      case (None, Some(true)) => None
      case (Some(true), Some(false)) => Some(FAILED)
      case (Some(true), None) => Some(UNKNOWN)
      case (Some(false), Some(false)) => None
      case (Some(false), None) => None
      case (None, Some(false)) => Some(UNKNOWN)
}

If any of the case statements above where missing, the Scala compiler would complain. Question is whether this is also the case for the Kotlin compiler.

If we use when as an expression, then it is exhaustive and it is checked for correctness at the compile time. But it is hard to discuss an example like above, because Kotlin doesn’t have (yet?) as advanced pattern matching as Scala, so the above code is not really translatable to Kotlin.

2 Likes