matcherror

How to use Lists in Scala match expressions

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.15, “How to use Lists in Scala match expressions.”

Problem

You know that a List data structure is a little different than other collection data structures. It’s built from “cons” cells and ends in a Nil element. You want to use this to your advantage when working with a match expression, such as when writing a recursive function.

How to access the value of the default case in a Scala match expression

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one of the shorter recipes, Recipe 3.10, “How to access the value of the default case in a Scala match expression.”

Problem

You want to access the value of the default, “catch all” case when using a match expression, but you can’t access the value when you match it with the _ wildcard syntax.

Solution

Instead of using the _ wildcard character, assign a variable name to the default case: