Using a lot ofmapandflatMapcan 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 afor-comprehension.
Afor-comprehensionallow you to chainmapandflatMaptogether 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 usingfor-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 withpattern matching, you can do within afor-comprehension. The left side of the<-behave similar to apattern matching.
Sometimes, it can be hard to convert in your head back and forth betweenfor-comprehensionandmapandflatMapmodes. Some IDEs, such as IntelliJ, starting with version 2020, allows you to de-sugar the code and convert thefor-comprehensionintomapandflatMap.