home search about rss feed twitter ko-fi

flatMap Naturally Leads to for-Expressions (Scala 3 Video)

“Since a type like Option that supports map and flatMap can be used in a for expression,” they thought, “What would happen if I do this?”:

val sum = for {
    x <- makeInt("1")
    y <- makeInt("2")
} yield x + y

The REPL shows the answer:

scala> val sum = for {
     |     x <- makeInt("1")
     |     y <- makeInt("2")
     | } yield x + y
sum: Option[Int] = Some(3)

“Whoa,” they thought, “not only does this give me the solution wrapped in only one Option, it’s also much easier to read than using map and flatMap.”

And then they thought, “Because it supports map and flatMap, it should work with more than two Option values, right?” So they put this code in the REPL:

val sum = for {
    a <- makeInt("1")
    b <- makeInt("2")
    c <- makeInt("3")
    d <- makeInt("4")
} yield a + b + c + d

and saw this result:

scala> val sum = for {
     |     a <- makeInt("1")
     |     b <- makeInt("2")
     |     c <- makeInt("3")
     |     d <- makeInt("4")
     | } yield a + b + c + d
sum: Option[Int] = Some(10)

Success!

This is much better than chaining together a whole bunch of flatMap and map functions, and it’s even easier to read than using a bunch of getOrElse calls.

And as you’re about to see, it’s also more flexible than getOrElse.

Update: All of my new videos are now on
LearnScala.dev