How to fix "Non exhaustive 'when' statements on sealed class/interface" in Kotlin

11k views Asked by At

Non exhaustive when statements on sealed class/interface will be prohibited in Kotlin 1.7.

I have a sealed class State and it's children:

sealed class State {
    object Initializing : State()
    object Connecting : State()
    object Disconnecting : State()
    object FailedToConnect : State()
    object Disconnected : State()
    object Ready : State()
}

In some cases I want to handle only particular items, not all, for example:

val state: State = ... // initialize
when (state) {
    State.Ready -> { ... }
    State.Disconnected -> { ... }
}

But I get a warning (in Kotlin 1.7 I guess it will be an error), saying:

Non exhaustive 'when' statements on sealed class/interface will be prohibited in 1.7, add 'Connecting', 'Disconnecting', 'FailedToConnect', 'Initializing' branches or 'else' branch instead

Is it a good practice to use empty else -> {} branch here like in the next code?

when (state) {
    State.Ready -> { ... }
    State.Disconnected -> { ... }
    else -> {}
}

Or need to add every item with an empty brackets like in the following code?

when (state) {
    State.Ready -> { ... }
    State.Disconnected -> { ... }
    State.Connecting,
    State.Disconnecting,
    State.FailedToConnect,
    State.Initializing -> {}
}
2

There are 2 answers

0
NSaran On

IMO, it is not a good practice to add else in when clauses when it's being used to compare subclasses of a sealed class.

When there is a breaking change due to addition of a new subclass you would want the compiler to highlight all the when comparisons so that you can go in and place appropriate logic or maybe do nothing at all use sites; either way it will be an informed decision. Instead, if we had just added else then the new subclass will get handled by it which might not what we want at all the use sites.

0
Viks On

In when statements, the else branch is mandatory in the following conditions:

  • when has a subject of a Boolean, enum, or sealed type, or their nullable counterparts.

  • branches of when don't cover all possible cases for this subject.

Source: https://kotlinlang.org/docs/control-flow.html#when-expression