9

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 -> {}
}
Sergio
  • 27,326
  • 8
  • 128
  • 149
  • Using _else_ as in your first example is fine. What you also can do is to use _if (state == State.Ready) { ... } else if (state == State.Disconnected) { ... }_ with no else clause. – lukas.j May 25 '22 at 15:07
  • 2
    That's really a personal/team preference thing IMHO. I would lean towards the latter approach, just as a reminder of what cases you are ignoring. – CommonsWare May 25 '22 at 15:11

1 Answers1

2

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

Viks
  • 1,510
  • 4
  • 22
  • 50