This is an excerpt from the 1st Edition of the Scala Cookbook (partially modified for the internet). This is Recipe 3.8, “How to match multiple patterns with one Scala case
statement.”
Scala 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 expression 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.
NOTE: I wrote all these example using the Scala 2 syntax, but they also work with Scala 3.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
See Also
- See Recipe 3.13, “Adding if Expressions (Guards) to Case Statements”, for a related approach