Another Scala nested Option + flatMap example

After yesterday’s Scala nested Option + flatMap/for example, here’s another example of plowing through nested Options with flatMap. First, start with some nested options:

val o1 = Option(1)
val oo1 = Option(o1)
val ooo1 = Option(oo1)

Here are those same three lines, with the data type for each instance shown in the comments:

val o1 = Option(1)       // Option[Int]
val oo1 = Option(o1)     // Option[Option[Int]]
val ooo1 = Option(oo1)   // Option[Option[Option[Int]]]

With this setup, just like yesterday, I can dig my way through the Options to get to the enclosed value using flatMap calls:

ooo1 flatMap { oo1 =>
    oo1 flatMap { o1 =>
        o1
    }
}

Here’s what that code looks like in the Scala REPL:

scala> val o1 = Option(1)
o1: Option[Int] = Some(1)

scala> val oo1 = Option(o1)
oo1: Option[Option[Int]] = Some(Some(1))

scala> val ooo1 = Option(oo1)
ooo1: Option[Option[Option[Int]]] = Some(Some(Some(1)))

scala> ooo1 flatMap { oo1 =>
     |     oo1 flatMap { o1 =>
     |         o1
     |     }
     | }
res0: Option[Int] = Some(1)

As that shows, the final result of the flatMap calls is an Option[Int], specifically a Some(1).

Just like yesterday, you can also use for-expressions to get to the enclosed value, but for today I just wanted to show this as another flatMap example.

I’ll keep trying to make monads, flatMap, and for-expressions as easy as I can, but for now I hope that’s a simple example you can experiment. (At least the setup portion of it is simple.)