Héc*_*tor 3 kotlin sealed-class
也许这是一个荒谬的问题.我有一个接收Command(密封类)并返回的方法Unit,我希望编译器崩溃是否所有when分支都没有实现:
sealed class Command
class FirstCommand : Command()
class SecondCommand: Command()
fun handle(cmd: Command) {
when(cmd) {
is FirstCommand -> //whatever
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码没问题,但我不想编译.
当方法返回任何不同的东西时Unit,它不会编译:
fun handle(cmd: Command) : Any {
when(cmd) { //error, when must be exhaustive and requires all branches
is FirstCommand -> //whatever
}
}
Run Code Online (Sandbox Code Playgroud)
我想要那种行为,但什么都不返回(Unit).我理解为什么会这样,但我想知道是否有任何方法可以改变我的代码来实现我想要的.我需要覆盖所有Command实现,而不会忘记以后可能添加的任何人.
解决了.return即使方法返回,我也不知道你可以使用语句Unit:
fun handle(cmd: Command) {
return when(cmd) {
is FirstCommand -> //whatever
}
}
Run Code Online (Sandbox Code Playgroud)
现在,上面的代码无法编译,因为when需要所有分支.正是我想要的.
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |