Scala 管道模式匹配作为变量

Scala pipe patternmatching as a variable

经常需要对多个值执行相同的代码。使用 match 这可以使用 | 来完成(管道)运算符:

val state = "stopped"
val value = 0
(state, value) match {
    case ("running" | "pending", 0)   => println("running with no value")
    case ("stopped" | "cancelled", 0) => println("not running; no value")
    case ("running" | "pending", _)   => println("running with a value")
    case ("stopped" | "cancelled", _) => println("not running with a value")
    case _                            => println("unknown state")
}

有没有办法把管道写成变量,eg:

val runningStates    = "running" | "pending"
val nonRunningStates = "stopped" | "cancelled"

所以我可以在上面的模式匹配中使用这些:

(state, value) match {
    case (runningStates, 0)    => println("running with no value")
    case (nonRunningStates, 0) => println("not running; no value")
    case (runningStates, _)    => println("running with a value")
    case (nonRunningStates, _) => println("not running with a value")
    case _                     => println("unknown state")
}

你的实际问题的答案是否定的,你不能把管道写成变量。

模式替代部分中的 Scala 语言参考 (8.1.12) 说:

A pattern alternative p1 | ... | pn consists of a number of alternative patterns pi. All alternative patterns are type checked with the expected type of the pattern. They may not bind variables other than wildcards. The alternative pattern matches a value v if at least one its alternatives matches v.

所以管道 | 没有在库中实现,但它由 Scala 编译器解释,并且它对模式匹配是上下文敏感的。