捕获“何时”值

k31*_*159 1 kotlin

有没有办法捕获控制语句中流程的值when

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

我们应该如何得到上面 所代表的值{???}呢?

luk*_*s.j 10

您可以将计算表达式的结果分配给常量并将其用作when子句的参数:

when(val result = ...your expression here...) {
  "one" -> println("two")
  "two" -> println("three")
  else -> println("Error: $result is not a recognised option.")
}
Run Code Online (Sandbox Code Playgroud)