3.9. Assigning the Result of a Match Expression to a Variable

Problem

You want to return a value from a 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

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.