Monads

In the above, flatMap binds stuff together. All the combinator blocks are closure blocks. The map block, for example, is accessing variables from its enclosing scopes. And all blocks are returning back a list of strings.

What does a flatMap do? It maps and then flattens the result. For example, the following is a way to pick up numbers from List[Any]. Using a map does not fully cut it:

scala> val l = List(1, "this", 2, 4.4, 'c')
l: List[Any] = List(1, this, 2, 4.4, c)

scala> l map {
     |   case i: Int => Some(i)
     |   case _ => None
     | }
res0: List[Option[Int]] = List(Some(1), None, Some(2), None, None)

We just need the numbers; however, we get them wrapped up in Some or we get them wrapped up in None. We have already seen both how we could collect ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.