If I have a sealed class, for example
sealed class Result {
object Success: Result()
object Failure: Result()
}
Why do when statements compile when they are not exhaustive, but when expressions don't compile?
when(getResult()) { // `when` doesn't show a red squiggly, compiles file
Result.Success -> {}
}
val result = when(getResult()) { // <--- when shows a red squiggly, doesn't compile
Result.Success -> {}
}
To make it a compile error for when statements, just call the exhaustive extension property:
when(getResult()) { // `when` NOW shows a red squiggly
Result.Success -> {}
}.exhaustive
I was watching YouTube: Sealed classes - Kotlin Vocabulary where they suggested using the following code to overcome this, but I want to understand why there is a difference. That should help me understand why the following Kotlin generic extension property solves the problem.
val <T> T.exhaustive: T
get() = this
EDIT: Thanks to Tenfour04, I know why. I just don't know why this exhaustive extension function does its job.