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 vs map and flatMap)


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, Option, flatMap, and map)


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

and this:

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

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.