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 -> {}
}
IMO, it is not a good practice to add
elseinwhenclauses 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
whencomparisons 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 addedelsethen the new subclass will get handled by it which might not what we want at all the use sites.