https://kotlinlang.org logo
#announcements
Title
# announcements
z

zak.taccardi

01/04/2021, 10:05 PM
Is it possible to return early from an exhaustive
when
?
s

streetsofboston

01/04/2021, 10:07 PM
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

FunkyMuse

01/04/2021, 10:14 PM
Can you share the use case?
n

Nir

01/04/2021, 10:48 PM
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

Marc Knaup

01/04/2021, 10:52 PM
You could use
break
then. Except in Kotlin/JS, there you should definitely avoid
break
in
when
inside a loop 😅
n

Nir

01/04/2021, 11:06 PM
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

zak.taccardi

01/05/2021, 2:58 AM
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

Nir

01/05/2021, 3:53 AM
@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

louiscad

01/05/2021, 10:29 AM
@Marc Knaup Why should
break
in
when
be avoided in Kotlin/JS?
m

Marc Knaup

01/05/2021, 11:34 AM
@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

louiscad

01/05/2021, 11:49 AM
Can you link it?
m

Marc Knaup

01/05/2021, 11:53 AM
26 Views