Home > front end >  Scala pipe patternmatching as a variable
Scala pipe patternmatching as a variable

Time:05-05

Often it is required to execute the same code for multiple values. With match this can be done using | (pipe) operator:

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")
}

Is there a method to write the pipes as a variable, eg:

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

So I can use these in the above pattern matching:

(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")
}

CodePudding user response:

The answer to your actual question is no, you can not write a pipe as a variable.

The Scala language reference in the Pattern Alternatives section (8.1.12) says:

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.

so the pipe | is not implemented in the library but it is interpreted by the Scala compiler and it is context sensitive to pattern matching.

  • Related