https://kotlinlang.org logo
m

Matej Kormuth

02/03/2019, 12:06 AM
It would be nice to have
it
or similar variable in
else
clause of
when
control structure.
Copy code
when (a()) {
    1 -> b()
    2 -> c()
    else -> d(it)
}
1
r

Ruckus

02/03/2019, 12:19 AM
You can assign in the statement:
Copy code
when (val res = a()) {
    ...
    else -> d(res)
}
The advantage of this as opposed to assigning a val before the when is that
res
is confined to the scope of the when.
🤩 1
👍 1
m

Marc Knaup

02/03/2019, 5:00 AM
I guess adding an implicit
it
would also break existing code where
when
together with
it
is used in a lambda. btw it's not just a problem with
else
but also the other branches. You don't have the value in the right type there unless you use the preferred approach Ruckus has mentioned.
x

xenoterracide

02/04/2019, 4:24 PM
death to syntax, when should be a method call! so should if
b

benleggiero

02/05/2019, 2:28 AM
@Ruckus!! I had no idea of that syntax!! Thank you!!
2 Views