Is it possible to return early from an exhaustive ...
# announcements
z
Is it possible to return early from an exhaustive
when
?
s
It should be. A
return
statement is an expression returning
Nothing
.
Copy code
val a: Int = when (value) {
    Hello -> 4
    There -> 6
    Bye -> return null
}
return "$a"
f
Can you share the use case?
n
it's not very hard to imagine use cases, e.g. you could have a
when
inside a loop that is used as part of the logic to iterate something, and perhaps one of the cases allows early exit
m
You could use
break
then. Except in Kotlin/JS, there you should definitely avoid
break
in
when
inside a loop 😅
n
not necessarily, it's two different situations... break is appropriate if you just need to get out of the loop. return is appropriate if you want to get out of the function.
I mean on the one hand I feel like I'm stating the obvious, on the other hand it apparently needs to be stated, so what can I say 🙂
z
sorry, yeah the idea is to break out of a when loop early
I know a
return@label
will work for functions, but idk how to label a
when
statement
this could be useful in a scenario where you have nested `when`/`if`s to reduce nesting
Copy code
val exhaustive = when {
    exception != null -> {
        if (something) {
            // return out of when early - does not work
            return@when somethingElse 
        }
        // carry on my wayward son
        Result.raise(exception)
    }
n
@zak.taccardi You can always enclose the when in a run block
And return to the run
Usually though you can refactor so it becomes more elegant than that
If you show a code sample that has the essential elements from your example may be able to suggest something
l
@Marc Knaup Why should
break
in
when
be avoided in Kotlin/JS?
m
@louiscad there's an open compiler bug. In KJS it breaks the when, not the loop.
At least in IR. No idea about legacy
l
Can you link it?
m