'When' with 'it'

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

6 Likes

I like this. It takes it another step closer to working like actual pattern matching, I think.

Look like it can’t be added now without breaking existing code.

See this comment: https://youtrack.jetbrains.com/issue/KT-4895#comment=27-1411580

That’s true. But the point is to inline assignment of when argument to variable. What about other options?

For instance lambda-style assignment:
`

when(v -> calculation()) {
    42 -> println("The meaning of life is revealed")
    else -> println("Life is $v")
}

`

Or inline declaration style:
`

when(val v = calculation()) {
    42 -> println("The meaning of life is revealed")
    else -> println("Life is $v")
}

`

Or labeled style:
`

when(calculation()) {
    42 -> println("The meaning of life is revealed")
    else -> println("Life is ${it@when}")
}

`

I know it’s uglier (especially due to multiple braces), but otherwise this currently working solution is workable:

  (x+4).let{ when(it) {
      42 -> println("The meaning of life is revealed")
      else -> println("Life is $it")
  }}
1 Like

There are options to be considered, but it’s unlikely that we’ll cover this issue in 1.1

It would be a good addition for 1.2 imo if it can somehow be fitted in.