There are 2 kinds of for in scala:

  1. for-loops
  2. for-comprehensions

for-loops

The for-loops is like for-loops in java

for (x <- xs) f(x)

is the same as:

xs.foreach(x => f(x))

for-comprehensions

This example shows how scala translate for comprehensions into term of expression map flatMap and filter.

  • A simple for-expression (1 generator)
for (x <- e1) yield e2

TO:

e1.map(x => e2)
  • A for-expression with if
for (x <- e1 if f; s) yield e2

TO:

for (x <- e1.withFilter(x => f); s) yield e2

and traslate continue until be a simple form

  • A for-expression with 2 generators
for (x <- e1; y <- e2; s) yield e3

TO:

e1.flatMap(x => for (y <- e2; s) yield e3)

and traslate continue until be a simple form

Example:

for {
  x <- 1 to N
  y <- 1 to x
  if (x % y == 0)
} yield (x, y)

to:

(1 to N) flatMap (x =>
  (1 to x) withFilter (y =>
    x % y == 0) map (y => (x, y)))