Thinking of a Scala Option as a List

Just wanted to show a tiny tidbit of cool and tidy codeā€”and this is one of those things that become intuitive as you start working with lists and flatMap (i.e. Monads, even if you don’t know the term yet) and working toward the wizardry of true FP.

So I’ve got a list (or Seq or similar collection) and I want to append an object to it. Something like:

val name: Option[String] = Some(Dude)
val greetingWords: Seq[String] = List(Hi, there, Dude)

But we’ve got the hitch that the object we want to append is an Option[String]. Maybe it comes from a “getName” function that may not be able to get a name. We could always write the code like this…

val name: Option[String] = Some("Dude")
val greetingWords: Seq[String] = Seq("Hi", "there") ++ { 
  name match {
    case Some(name) => Seq(name)
    case None => Seq.empty[String]
  }
}

…but that’s ugly and inelegant.

So here’s the elegant way of approaching this: Option[A] can be thought of as a special kind of list that has either one or zero values, depending on whether it’s a Some or a None! So in fact, you can save a lot of the code and add the option as though it were another Seq…

scala> Seq("hi","there") ++ Some("dude")
val res3: Seq[String] = List(hi, there, dude)

scala> Seq("hi","there") ++ None
val res4: Seq[String] = List(hi, there)

Clever, huh?

Author: Murray Todd Williams

I live in Austin, Texas. I'm enthusiastic about food, wine, programming (especially Scala), tennis and politics. I've worked for Accenture for over 12 years where I'm a Product Manager for suite of analytical business applications.