1

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.

testivanivan
  • 967
  • 13
  • 36
  • How about not having an `else` at all? – Sweeper Nov 15 '22 at 13:37
  • When using enum inside `when` block from Kotlin 1.7 we need to add else branch or branches with all elements of the enum – testivanivan Nov 15 '22 at 13:43
  • 1
    Your `when` expression returns `Unit` so a couple of options are `else -> {}` and `else -> Unit`. The example with `Int` is a bit misleading because the compiler won't enforce exhaustiveness in that case. – gpunto Nov 15 '22 at 13:44
  • @testivanivan Huh, you're right. Weird that I didn't find this in the spec. But the example in your question uses an `Int` though. – Sweeper Nov 15 '22 at 13:50
  • 2
    Java's `break` from switch statements is the default behaviour in Kotlin, you don't need `break` in any branch. If you really need to express "do nothing" you can use `Unit` – Joffrey Nov 15 '22 at 14:59
  • gpunto, Yes, you are right, my example is not entirely correct and confusing. But in this case, the Unit suits me, thanks for the help. – testivanivan Nov 15 '22 at 15:04
  • FWIW, I see nothing at all wrong with `-> {}` — for me, it's clearer than any of the alternatives so far (including `-> Unit`, which is more long-winded and a little harder to follow, especially for non-experts). – gidds Nov 15 '22 at 19:48

1 Answers1

1

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313