Wouldn’t it be cool to access the calculation
result as predefined variable it
in flow branches of when(calculation())
? Similar to it
in: listOf(1, 2, 3).all { it > 0 } }
.
In the following snippet fun haveBreakfast
uses when
in classic way forcing to assign variable if i need to use it in branches. But fun haveDinner
(which will not be compiled of course) uses when
in more concise (suggested) way .
`
fun main(args: Array<String>) {
Me.haveBreakfast()
}
interface Thing
class Snickers : Thing
class Sneakers : Thing
object Me {
val myFridge = listOf<Thing>(Snickers(), Sneakers(), Snickers())
fun haveBreakfast() {
val it = myFridge[Random(2).nextInt()]
when (it) {
is Snickers -> Me.eat(it)
is Sneakers -> Me.wonder(it)
else -> println("WTF?!")
}
}
fun haveDinner() = when (myFridge[Random(2).nextInt()]) {
is Snickers -> Me.eat(it)
is Sneakers -> Me.wonder(it)
else -> println("WTF?!")
}
fun eat(v: Snickers) { println("Yummy") }
fun wonder(v: Sneakers) { println("What does it do in my fridge?") }
}
`
Is it planned / possible to implement?
Related feature request KT-11942