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.
First of all, you don't need an
else
here, as this is awhen
statement, with the bound value being anInt
. It would need to be exhaustive in situations like thisSo 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:Now you can do:
This is super confusing though, since
break
in Kotlin has typeNothing
, rather thanUnit
. Do this at your own risk.