Scala List pattern matching

Let's see howListis used in the context ofpattern matching.

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

First we have to talk about howListcan be created and modified.

Everything is immutable which is why we always create a newList, 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 forList.empty[A]
  • ::: to add an element at the start of aList, which is why to create aListusing this operator, we have to finish byNil. We actually prepend element to an empty list.
  • +:: to prepend an element to theList. Same as::.
  • :+: to append an element at the end of aList

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

Pattern matchingnow

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

For instance, we cancase head :: tail =>to extract the first element of the list. We can also docase 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 otherpattern matchingconstruct, we can add conditions to all those patterns. Either by addingifat 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 a1. Andcase 1 :: Nil =>will match on a list containing one element being1.

Reveal more information and clues
Load Exercise