【发布时间】: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