如何修复 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)

Vik*_*uli 2

when语句中,else分支在以下情况下是强制性的:

  • whenBoolean具有 a 、enum、 或类型的主题sealed,或其可为空的对应项。

  • 的分支when并不涵盖该主题的所有可能情况。

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