Scala headOption example

The scala collections API provides a function called “headOption”, which returns a Some(value) if there is an item in a list, and a “None” otherwise.

Observe:

scala> List(1).headOption
res35: Option[Int] = Some(1)

scala> List().headOption
res36: Option[Nothing] = None

It may not be immediately obvious why this is useful, especially if you’re coming from Java, or similar languages.

However, it is quite useful, because you can use it to detect the end-of-sequence condition (without knowing why the sequence ends – it’d behave the same if it was a network socket, as if it was an array)

For instance, lets say you decided to count the number of items in the sequence, using recursion. If you did this, you could pattern match the value of headOption to see if you were done:

val count: (Seq[Any]) => Int = 
  (values: Seq[Any]) => { 
    values.headOption match { 
      case Some(_) => 1 + count(values.tail) 
      case None => 0 
    }
  }

scala> count(List(1,2,3))
res37: Int = 3