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

Interested in Scala? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *