Home > database >  Capturing the 'when' value
Capturing the 'when' value

Time:11-29

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 {???}?

CodePudding user response:

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.")
}
  • Related