Scala List pattern matching

Let's see how List is used in the context of pattern matching.

This is a pre-requirement to talk about recursion later on.

First we have to talk about how List can be created and modified.

Everything is immutable which is why we always create a new List, we don't update the previous one.

A few new operator today:

  • Nil: not really an operator, but it describe an empty list, it is a short cut for List.empty[A]
  • ::: to add an element at the start of a List, which is why to create a List using this operator, we have to finish by Nil. We actually prepend element to an empty list.
  • +:: to prepend an element to the List. Same as ::.
  • :+: to append an element at the end of a List

If know that +: and :+ can be confusing but you simply have to remember that : is towards the List.

Pattern matching now

Using the :: we can extract head element(s) from the List.

For instance, we can case head :: tail => to extract the first element of the list. We can also do case a :: b :: tail => to extract the two first element of the list. We can continue with as many as we would like.

Similarly to all the other pattern matching construct, we can add conditions to all those patterns. Either by adding if at the end or by replacing a value name by a literal value, for instance: case 1 :: tail => will match on any list that start by a 1. And case 1 :: Nil => will match on a list containing one element being 1.

Reveal more information and clues
Load Exercise