O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required