Scala: How to match multiple conditions (patterns) with one case statement

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.8, “How to match multiple patterns with one case statement.”

Problem

You have a situation in your Scala code where several match conditions/patterns require that the same business logic be executed, and rather than repeating your business logic for each case, you’d like to use one copy of the business logic for the matching conditions.

Solution

Place the match conditions that invoke the same business logic on one line, separated by the | (pipe) character:

val i = 5
i match {
    case 1 | 3 | 5 | 7 | 9 => println("odd")
    case 2 | 4 | 6 | 8 | 10 => println("even")
}

This same syntax works with strings and other types. Here’s an example based on a String match:

val cmd = "stop"
cmd match {
    case "start" | "go" => println("starting")
    case "stop" | "quit" | "exit" => println("stopping")
    case _ => println("doing nothing")
}

This example shows how to match multiple case objects:

trait Command

case object Start extends Command
case object Go extends Command
case object Stop extends Command
case object Whoa extends Command

def executeCommand(cmd: Command) = cmd match {
    case Start | Go => start()
    case Stop | Whoa => stop()
}

As demonstrated, the ability to define multiple possible matches for each case statement can simplify your code.

See Also

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.