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.”


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.


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

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:

This website is a little one-man operation. If you found this information helpful, I’d appreciate it if you would share it.

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.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.