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.