如何修复 Kotlin 中的“密封类/接口上的非详尽‘when’语句”

Ser*_*gey 9 android kotlin sealed-class kotlin-when kotlin-sealed

Kotlin 1.7when中将禁止对密封类/接口进行非详尽的声明。

我有一个sealed class State和它的孩子:

sealed class State {
    object Initializing : State()
    object Connecting : State()
    object Disconnecting : State()
    object FailedToConnect : State()
    object Disconnected : State()
    object Ready : State()
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,我只想处理特定的项目,而不是全部,例如:

val state: State = ... // initialize
when (state) {
    State.Ready -> { ... }
    State.Disconnected -> { ... }
}
Run Code Online (Sandbox Code Playgroud)

但我收到一条警告(在Kotlin 1.7中我猜这将是一个错误),说:

1.7 中将禁止在密封类/接口上使用非详尽的“when”语句,而是添加“Connecting”、“Disconnecting”、“FailedToConnect”、“Initializing”分支或“else”分支

else -> {}像下面的代码一样在这里使用空分支是一个好习惯吗?

when (state) {
    State.Ready -> { ... }
    State.Disconnected -> { ... }
    else -> {}
}
Run Code Online (Sandbox Code Playgroud)

或者需要添加带有空括号的每个项目,如下面的代码所示?

when (state) {
    State.Ready -> { ... }
    State.Disconnected -> { ... }
    State.Connecting,
    State.Disconnecting,
    State.FailedToConnect,
    State.Initializing -> {}
}
Run Code Online (Sandbox Code Playgroud)