【问题标题】:How to fix "Non exhaustive 'when' statements on sealed class/interface" in Kotlin如何在 Kotlin 中修复“非详尽的 \'when\' 密封类/接口\”语句
【发布时间】:2022-10-18 10:16:58
【问题描述】:

在密封类/接口上的非详尽 when 声明将被禁止科特林 1.7.

我有一个sealed class State,它是孩子们:

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

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

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

但我收到警告(在科特林 1.7我想这将是一个错误),说:

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

像在下一个代码中一样在此处使用空的else -> {} 分支是一种好习惯吗?

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

或者需要像下面的代码一样添加带有空括号的每个项目?

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

【问题讨论】:

  • 使用别的就像你的第一个例子一样。你也可以做的是使用if (state == State.Ready) { ... } else if (state == State.Disconnected) { ... }没有其他条款。
  • 恕我直言,这确实是个人/团队偏好的事情。我倾向于后一种方法,就像提醒您忽略了哪些情况一样。

标签: android kotlin sealed-class kotlin-when kotlin-sealed


【解决方案1】:

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

  • when 的主题为 Booleanenumsealed 类型,或其可为空的对应对象。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 2019-05-05
    相关资源
    最近更新 更多