O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

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

Puzzler 8

Map Comprehension

Scala's for comprehensions provide an elegant syntax for invocations of powerful functional constructs based on map and flatMap. In Scala, for comprehensions are so widespread that understanding how they are desugared to map, flatMap, withFilter, and foreach calls is a common exercise when learning the language. This is especially useful because it may sometimes be preferable to desugar a for comprehension "by hand," if only for debugging purposes.

In this puzzler, we compare a for comprehension that also uses a pattern match with a desugared version of the same for expression obtained by transforming:

  for (i <- expr) yield fun(i)

to:

  expr map { i => fun(i) }

What is the result of executing the following code in ...

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