Scala: A look at flatMap and map on Option

As a quick Scala tip, if you haven’t worked with the flatMap on an Option much, it can help to know that flatMap’s function should return an Option, which you can see in this REPL example:

scala> Some(1).flatMap{ i => Option(i) }
res0: Option[Int] = Some(1)

You can tell this by looking at the function signature in the scaladoc for the flatMap method on the Option class:

flatMap[B](f: (A) => Option[B]): Option[B]
           -------------------

map on Option

Conversely, the function you pass to map on Option should simply transform the given type A to another type B:

map[B](f: (A) => B): Option[B]
       -----------

You can demonstrate this in the REPL:

scala> Some(1).map{ i => i }
res1: Option[Int] = Some(1)

Both map and flatMap return an Option in the end, but these examples show the difference between the custom functions you should pass into flatMap and map: flatMap should return an Option, and map should return a simple type that’s not wrapped in an Option.