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)

this:

val y = x.map(_ * 2)

and this:

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

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

this:

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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.