Option and flatMap

What is an Option anyway?

One of the things that confused me when I first started learning about the Option type in Scala was that I couldn't understand why it was possible to call flatMap and flatten on an Option type.

It turns out that Option[T] can be considered a special type of collection with two possible values - either a collection with zero elements, or a collection with exactly one value of type T.

It's possible in Scala to convert an Option into a list, by calling the toList method on it, which yields some interesting results:

scala> val opt = Some("bunny")
opt: Some[String] = Some(bunny)
scala> opt.toList
res5: List[String] = List(bunny)

scala> val noBunny = None
noBunny: None.type = None
scala> noBunny.toList
res6: List[Nothing] = List()

Indeed, we can see that the None value yields the empty list, and that the Some value yields a list with one element.

So what does that mean?

Now we know that Option can be treated as a collection, it means we get to use them in a functional way, and all the funtional operators like map and flatMap apply.

One particular use case I came across was where I wanted to do some processing on a List[User] where User had an Option[String] type as its username. I didn't want to do the processing if the username value was None. Here's the code:

As you can see, I'm using flatMap to convert any None values to the empty List and effectively remove them from my processing.

I have also included the flatMap and map version converted to using for comprehensions which you may find a little easier to read, although to the Scala beginner they often look a little magical.