Using a lot of map
and flatMap
can make the code very hard to read as it goes into deep functions of functions.
Scala has a way of handling those cases. It is called a for-comprehension.
A for-comprehension allow you to chain map
and flatMap
together in an easy to read form.
For instance, those two snippets of code are equivalent:
andfor { n <- list }
yield n + 1
list.map( n => n + 1 )
You can also filter the input using for-comprehension.
This snippet is equivalent to:for {
n <- list
if n == 2
} yield n
input.withFilter(n => n == 2)
In general, everything you can do with pattern matching, you can do within a for-comprehension. The left side of the <-
behave similar to a pattern matching.
Sometimes, it can be hard to convert in your head back and forth between for-comprehension and map
and flatMap
modes. Some IDEs, such as IntelliJ, starting with version 2020, allows you to de-sugar the code and convert the for-comprehension intomap
and flatMap
.