我需要break
像在Java从when
分支。从Kotlin 1.7.0我得到错误
当表达式必须是穷举式
现在我需要添加一个分支else
。在else
中,我想从when
中退出。
我可以使用return,但是在这种情况下,when
块之后的所有代码都不会被执行,我们将退出整个函数。下面是一个例子:
private fun testFun(a: Int) {
when(a) {
5 -> println("this is 5")
10 -> println("this is 10")
else -> return
}
println("This is end of func") // this will not call
}
我给出了这个代码片段作为示例。当将when
与枚举或布尔值一起使用时,这个问题是相关的。
我也可以使用这种结构:else ->{}。但我看不太清楚。请告诉我是否有任何方式来执行默认:break;
首先,这里不需要else
,因为这是一个when
语句,绑定值是Int
。在这种情况下需要是详尽的
val someValue = when(a) {
5 -> "this is 5"
10 -> "this is 10"
else -> "something else" // now you need the "else" branch
}
所以你一开始就不需要写else -> {}
也就是说,如果您出于某种原因非常想在这里写单词break
,您可以定义:
val `break` = Unit
现在你可以这样做:
// yes, this means you can also do "else -> Unit"
// but if you find "else -> {}" unclear, "else -> Unit" will probably be even more so
else -> `break`
这是超级令人困惑的,因为在Kotlin中break
的类型是Nothing
,而不是Unit
。请自行承担风险。