Scala for-comprehension

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:

for { n <- list }

yield n + 1

and n => n + 1 )

You can also filter the input using for-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 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.

Reveal more information and clues
Load Exercise