也许这是一个荒谬的问题。我有一个接收 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
实现,同时不要忘记以后可能添加的任何人。
最佳答案
已解决。我不知道即使方法返回 Unit
也可以使用 return
语句:
fun handle(cmd: Command) {
return when(cmd) {
is FirstCommand -> //whatever
}
}
现在,上面的代码无法编译,因为 when
需要所有分支。正是我想要的。
关于kotlin - 当 "when"语句未涵盖所有实现时,强制编译器发出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50935149/