Sealed classes and when expressions


#1

The documentation states:

The key benefit of using sealed classes comes into play when you use them in a when expression. If it’s possible to verify that the statement covers all cases, you don’t need to add an else clause to the statement.

But that seems not to be true, since this examples compiles without any error or warning:

sealed class Direction
object Left : Direction()
object Right : Direction()


fun main(args: Array<String>) {
    decide(Right)
}

fun decide(direction: Direction) {
    when(direction) {
        is Left -> println("L")
        //is Right -> println("R")
    }
}

I tried it with Kotlin 1.2-M1.

What is wrong: my code, the documentation or the compiler?


#2

You’re actually using a ‘when’ statement in your code rather than a ‘when’ expession.

If you assign it to a variable, I think you’ll find that it works as the documentation indicates.


#3

You’re right, thanks! The following results in the desired compiler error :wink:

val abbreviation = when(direction) {
    is Left -> "L"
    //is Right -> "R"
}

#4

That’s a very important distinction that isn’t immediately obvious. This is very useful to know!

Perhaps the documentation can also highlight this a bit more explicitly.


#5

I discovered this very recently and I was also surprised.

My solution is to do:
when (object) { … }.let {}

This avoids the warning on an unused variable.