Scala: How to assign the result of a match expression to a variable

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one of the shortest recipes, Recipe 3.9, “How to assign the result of a match expression to a variable.”

Problem

You want to return a value from a Scala match expression and assign it to a variable, or use a match expression as the body of a method.

Solution

To assign a variable to the result of a match expression, insert the variable assignment before the expression, as with the variable evenOrOdd in this example:

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

This approach is commonly used to create short methods or functions. For example, the following method implements the Perl definitions of true and false:

def isTrue(a: Any) = a match {
    case 0 | "" => false
    case _ => true
}

You’ll hear that Scala is an “expression-oriented programming (EOP) language,” which Wikipedia defines as, “a programming language where every (or nearly every) construction is an expression and thus yields a value.” The ability to return values from if statements and match expressions helps Scala meet this definition.

See Also

  • Recipe 20.3, “Think “Expression-Oriented Programming””
  • The Expression-Oriented Programming page on Wikipedia