I need break like in Java from when branch. From Kotlin 1.7.0 I get error
when expression must be exhaustive
Now I need to add a branch else. Inside else I want to just exit from when.
I can use a return, but in this case, all the code after the when block will not be executed and we will exit the entire function. Here is an example:
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
}
I gave this code snippet as an example. The problem is relevant when using when with enums or boolean.
I can also use this construct: else -> {}. But it doesn't look very clear to me. Please tell me if there is any way to perform default: break; as we did in Java.
CodePudding user response:
First of all, you don't need an else here, as this is a when statement, with the bound value being an Int. It would need to be exhaustive in situations like this
val someValue = when(a) {
5 -> "this is 5"
10 -> "this is 10"
else -> "something else" // now you need the "else" branch
}
So you don't have to write else -> {} in the first place.
That said, if you desperately want to write the word break in here for some reason, you can define:
val `break` = Unit
Now you can do:
// 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`
This is super confusing though, since break in Kotlin has type Nothing, rather than Unit. Do this at your own risk.
