Notes on Scala for expressions, map, flatMap, and Option

Without any explanation, these are some of my working notes from my upcoming book on Scala and Functional Programming about a) for expressions, b) map, c) flatMap, d) Option, and e) nested flatMap and map calls.

These are equivalent (map and for)


val y = * 2)

and this:

y = for {
    i <- x
} yield i * 2

These are equivalent (for-expression vs flatMap and map)


val z = for {
    xi <- x
    yi <- y
} yield xi * yi

and this:

val z = x flatMap { xi =>
    y map { yi =>
        xi * yi

These are equivalent (for-expression compared to flatMap and map)

This for-expression:

val x = for {
    i <- Option(3)
    j <- Option(4)
} yield i * j

is the same as this use of flatMap and map:

val x = Option(3) flatMap { i =>
    Option(4) map { j =>
        i * j

The crux of this last example is that flatMap knows how to extract a value out of an Option, and then passes that value into the anonymous function that follows. I show that better in my Handling nested Scala Options with flatMap and for tutorial.

For more examples, see the “Related” section below, and my collection of Scala flatMap examples.