20.4. Use Match Expressions and Pattern Matching

Problem

Match expressions (and pattern matching) are a major feature of the Scala programming language, and you want to see examples of the many ways to use them.

Solution

Match expressions (match/case statements) and pattern matching are a major feature of the Scala language. If you’re coming to Scala from Java, the most obvious uses are:

  • As a replacement for the Java switch statement

  • To replace unwieldy if/then statements

However, pattern matching is so common, you’ll find that match expressions are used in many more situations:

  • In try/catch expressions

  • As the body of a function or method

  • With the Option/Some/None coding pattern

  • In the receive method of actors

The following examples demonstrate these techniques.

Replacement for the Java switch statement and unwieldy if/then statements

Recipe 3.8 showed that a match expression can be used like a Java switch statement:

val month = i match {
  case 1  => "January"
  case 2  => "February"

  // more months here ...

  case 11 => "November"
  case 12 => "December"
  case _  => "Invalid month"  // the default, catch-all
}

It can be used in the same way to replace unwieldy if/then/else statements:

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

These are simple uses of match expressions, but they’re a good start.

In try/catch expressions

It helps to become comfortable with match expressions, because you’ll use them with Scala’s try/catch syntax. The following example shows how ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.