Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing the 'when' value

Tags:

kotlin

Is there a way to capture the value that controls the flow in a when statement?

when(some expression) {
    "one" -> println("two")
    "two" -> println("three")
    else -> println("Error: ${???} is not a recognised option.")
}

How should we get the value represented above by {???}?

like image 654
k314159 Avatar asked Jun 14 '26 18:06

k314159


1 Answers

You can assign the result of the evaluated expression to a constant and use it as argument to the when clause:

when(val result = ...your expression here...) {
  "one" -> println("two")
  "two" -> println("three")
  else -> println("Error: $result is not a recognised option.")
}
like image 173
lukas.j Avatar answered Jun 18 '26 01:06

lukas.j



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!