Translates

How to say it in other languages, and what words mean

Spanish

Scala for Loops & foreach: Compiler Translation

· 5 min read · Spanish

In this article
  1. Background: Why Scala Has Both for and foreach
  2. How the Compiler Translates a Simple for Loop
  3. Translation with yield: From for to map/flatMap
  4. How foreach Itself Is Implemented
  5. Choosing Between for and foreach in Code
  6. Common Pitfalls and Misconceptions
  7. Comparison with Java's Enhanced For Loop
  8. Frequently Asked Questions

In Scala, a for loop and a foreach call are both translated by the compiler into method calls on collections, but they are not identical: a for loop without yield becomes a call to foreach on the collection, while a for loop with yield becomes a call to map or flatMap (with withFilter for guards). The compiler desugars the syntactic sugar of for into these higher-order methods, which are then executed by the underlying collection's implementation.

Background: Why Scala Has Both for and foreach

Scala inherited the for loop syntax from Java and C, but it also adopted functional programming idioms like foreach. The language designers wanted to keep the familiar imperative syntax while encouraging a more functional style. The key insight is that for is not a built-in control structure in Scala—it is syntactic sugar that the compiler rewrites into method calls. This allows the same for syntax to work on any type that provides foreach, map, flatMap, and withFilter methods, including custom collections, Option, Future, and even your own classes.

How the Compiler Translates a Simple for Loop

Consider this typical loop:

for (i <- 1 to 10) println(i)

The compiler desugars it to:

(1 to 10).foreach(i => println(i))

More precisely, the for expression is rewritten as a call to foreach on the generator expression (1 to 10), passing a function literal that contains the loop body. The <- symbol is replaced by a lambda parameter. If there are multiple generators, they are nested: for (i <- 1 to 3; j <- 1 to 3) println(i + j) becomes (1 to 3).foreach(i => (1 to 3).foreach(j => println(i + j))).

Translation with yield: From for to map/flatMap

When you add yield, the loop becomes a comprehension that produces a new collection. For example:

val squares = for (i <- 1 to 5) yield i * i

This is translated to:

val squares = (1 to 5).map(i => i * i)

With multiple generators, the translation uses flatMap for all but the last generator, and map for the last:

for (i <- 1 to 2; j <- 1 to 3) yield (i, j)

becomes:

(1 to 2).flatMap(i => (1 to 3).map(j => (i, j)))

If you add a guard (an if condition), the compiler inserts withFilter instead of filter to avoid creating an intermediate collection:

for (i <- 1 to 10 if i % 2 == 0) yield i

becomes:

(1 to 10).withFilter(i => i % 2 == 0).map(i => i)

How foreach Itself Is Implemented

foreach is a method defined on all collection types (via TraversableLike or IterableOnce). Its implementation varies by collection: for an Array or List, it typically uses a while loop internally; for a Range, it uses a simple counter loop. The Scala compiler does not translate foreach into a loop—it leaves it as a method call. However, the JIT compiler (HotSpot) may inline the method and then optimize it into a native loop, so the performance is often comparable to a hand-written while loop.

Choosing Between for and foreach in Code

Since for without yield desugars to foreach, the choice is mostly stylistic. However, there are practical differences:

  • Readability: for loops with multiple generators and guards are often clearer than nested foreach calls with conditionals.
  • Side effects: If you need to perform side effects (like printing), foreach is explicit about that intent, while for without yield also signals side effects but can be confused with a comprehension.
  • Performance: There is no meaningful difference after compilation—both end up calling the same foreach method. But using while loops directly can be faster in tight loops because it avoids closure allocation, though the JIT often eliminates that overhead.
  • Functional style: Prefer for with yield for transformations, and foreach for side-effecting operations. Avoid using for without yield in purely functional code, as it is imperative in nature.

Common Pitfalls and Misconceptions

One frequent misconception is that for loops are slower than while loops. In practice, the Scala compiler often optimizes simple for loops into while loops during bytecode generation, especially for Range. Another pitfall is using for with yield on a Stream or infinite collection—this will attempt to build an infinite structure. Also, remember that for on Option works because Option has foreach, map, and flatMap, but it behaves differently: if the Option is None, the loop body is skipped, and with yield it returns None.

Comparison with Java's Enhanced For Loop

Java's enhanced for loop (for (int i : list)) is compiled into an iterator-based loop, while Scala's for is compiled into method calls. This means Scala's for can work with any type that defines the right methods, not just arrays and Iterable. For example, you can write for (x <- Some(42)) println(x) because Option has foreach. Java's loop cannot do that. Also, Scala's for with yield has no direct Java equivalent—you would need streams or manual collection building.

Frequently Asked Questions

Does for without yield always become foreach?

Yes, in the standard Scala 2 and Scala 3 compilers, a for loop without yield is desugared to nested foreach calls. If the generator is a Range, the compiler may further optimize it to a while loop, but the initial translation is always to foreach.

Can I see the translated code?

Yes, you can use the Scala compiler flag -print (or -Xprint:typer in Scala 2) to see the desugared code after type checking. For example, scalac -print MyFile.scala will show the foreach calls. In Scala 3, use scalac -Xprint:typer.

Is foreach a keyword in Scala?

No, foreach is a regular method name defined on collections. You can call it on any object that has a method named foreach with the right signature, which is how the compiler's desugaring works.

What happens if I use for on a custom class?

If your class defines foreach, map, flatMap, and withFilter with the appropriate signatures, you can use for comprehensions on it. This is how libraries like Future and Option integrate with for.

Does Scala 3 change the translation?

Scala 3 uses the same desugaring rules as Scala 2, but the internal compiler pipeline differs. The resulting method calls are the same, though Scala 3 may apply additional optimizations. The -Xprint:typer flag still works to show the translation.

Why does my for loop with a guard create a new collection?

When you use if inside a for comprehension, the compiler calls withFilter, which is a lazy filter that does not build an intermediate collection. However, if you use filter explicitly, it will create a new collection. The withFilter method is designed to avoid that overhead.