【问题标题】:Force compiler to emit an error when not all implementations are covered in "when" statement当“when”语句未涵盖所有实现时,强制编译器发出错误
【发布时间】:2018-06-19 18:49:22
【问题描述】:

也许这是一个荒谬的问题。我有一个接收Command(密封类)并返回Unit的方法,我希望编译器崩溃是否所有when分支都没有实现:

sealed class Command
class FirstCommand : Command()
class SecondCommand: Command()

fun handle(cmd: Command) {
  when(cmd) {
    is FirstCommand -> //whatever     
  }
}

上面的代码没问题,但我不希望它编译。

当方法返回与Unit 不同的任何内容时,它不会编译:

fun handle(cmd: Command) : Any {
  when(cmd) { //error, when must be exhaustive and requires all branches
    is FirstCommand -> //whatever     
  }
}

我想要这种行为,但什么也不返回 (Unit)。我理解为什么会发生这种情况,但我想知道是否有任何方法可以更改我的代码以实现我想要的。我需要涵盖所有Command 实现,不要忘记以后可能添加的任何人。

【问题讨论】:

  • 关于术语的一点:你不希望编译器崩溃!您只希望它发出错误消息。编译器只有在它本身有错误时才会崩溃。
  • @DodgyCodeException 绝对! ;D 感谢您的澄清

标签: kotlin sealed-class


【解决方案1】:

解决了。我不知道即使方法返回Unit,您也可以使用return 语句:

fun handle(cmd: Command) {
  return when(cmd) {
    is FirstCommand -> //whatever     
  }
}

现在,上面的代码无法编译,因为when 需要所有分支。正是我想要的。

【讨论】:

  • 您在此过程中丢失了返回类型(可能是拼写错误)
  • @Zoe 其实我返回的是“void”(单位)
  • 你有Any作为问题的返回类型,只是想确保它不是一个错字:)
  • @Zoe 这只是为了澄清,如果有返回类型,编译器 cmplains。但我的“真实”代码返回 Unit。还是谢谢
猜你喜欢
  • 2022-10-07
  • 1970-01-01
  • 2014-02-14
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2021-12-05
  • 1970-01-01
相关资源
最近更新 更多