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

If you want a good book on Scala, take a look at Programming Scala (I'm currently reading through this).

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 *