Using a lot ofmap
andflatMap
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 afor-comprehension.
Afor-comprehensionallow you to chainmap
andflatMap
together in an easy to read form.
For instance, those two snippets of code are equivalent:
for { n <- list } yield { n + 1 }and
list.map( n => n + 1 )
You can also filter the input usingfor-comprehension.
for { n <- list if n == 2 } yield { n }This snippet is equivalent to:
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-comprehensionandmap
andflatMap
modes. Some IDEs, such as IntelliJ, starting with version 2020, allows you to de-sugar the code and convert thefor-comprehensionintomap
andflatMap
.