Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 37 ยท Language Basics

Loops and For Comprehensions

Learn Scala 3 for loops and for comprehensions: ranges, guards, nested generators, yield, foreach vs map, while, and how for desugars into map and flatMap.

Scala's for is more than a counting loop. In its simplest form it repeats work for each item. With yield it becomes a comprehension that builds a new collection. Under the hood both are translated into calls to foreach, map, flatMap and withFilter, which means for works on lists, options, futures and any type that provides those methods. Here you will learn the loop forms, then the comprehension form, with read-only Scala and runnable Java/Kotlin comparisons.

A for loop over a range

SCALA
for i <- 1 to 3 do
  println(s"Round $i")
TEXT
Round 1
Round 2
Round 3

1 to 3 is an inclusive range (1, 2, 3). 1 until 3 excludes the end (1, 2). by sets a step:

SCALA
for i <- 10 to 1 by -3 do print(s"$i ")   // 10 7 4 1
for i <- 0 until 10 by 5 do print(s"$i ")  // 0 5

The old braces-and-parentheses form still works and is common in Scala 2 code:

SCALA
for (i <- 1 to 3) println(i)

Loop over the items of any collection:

SCALA
val fruits = List("apple", "pear", "plum")
for fruit <- fruits do println(fruit.toUpperCase)

The Kotlin equivalent, runnable:

Kotlin Looping over a range and a list (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Guards

Add an if to skip items:

SCALA
for
  n <- 1 to 10
  if n % 2 == 0
do println(n)          // 2 4 6 8 10 (one per line)

Generators and guards can be listed on separate lines, which is how longer loops are written.

Nested generators

Several <- generators nest like loops inside loops, with the last one varying fastest:

SCALA
for
  row <- 1 to 2
  col <- 1 to 3
do println(s"($row,$col)")
TEXT
(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)

You can also define a value in the middle of the loop with =:

SCALA
for
  n <- 1 to 4
  square = n * n
  if square > 4
do println(s"$n -> $square")

This prints 3 -> 9 and 4 -> 16.

for with yield: comprehensions

Add yield instead of do to collect the results:

SCALA
val squares = for n <- 1 to 5 yield n * n
// Vector(1, 4, 9, 16, 25)

val evenSquares =
  for
    n <- 1 to 10
    if n % 2 == 0
  yield n * n
// Vector(4, 16, 36, 64, 100)

The result type follows the source: a List in gives a List out, a Range gives a Vector, a Set gives a Set, and a String of characters can give a String or a Vector[Char] depending on the yielded value.

SCALA
val pairs =
  for
    x <- List(1, 2)
    y <- List("a", "b")
  yield (x, y)
// List((1,a), (1,b), (2,a), (2,b))

Java has no comprehension, so a streams version of the same pairing is a runnable contrast. Notice the extra ceremony:

Java Pairs with nested loops (Java comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

How for desugars

The compiler rewrites comprehensions into method calls. This is the key to understanding why for works on many types:

SCALA
// What you write
for x <- xs if x > 0 yield x * 2

// What the compiler produces (roughly)
xs.withFilter(x => x > 0).map(x => x * 2)

// Nested generators become flatMap
for x <- xs; y <- ys yield (x, y)
// xs.flatMap(x => ys.map(y => (x, y)))

// Without yield, foreach is used
for x <- xs do println(x)
// xs.foreach(x => println(x))

So any type that defines map, flatMap and (for guards) withFilter can be used in a for. Option, Future and Either do. See collection transformations for these methods.

Example: Option in a for

SCALA
def parse(s: String): Option[Int] = s.toIntOption

val total =
  for
    a <- parse("20")
    b <- parse("22")
  yield a + b
// Some(42)

If either parse returns None, the whole result is None and no exception is thrown. This pattern shows up all the time in real Scala.

while and do/while

while is available when the number of rounds depends on a changing condition:

SCALA
var n = 27
var steps = 0
while n != 1 do
  n = if n % 2 == 0 then n / 2 else 3 * n + 1
  steps += 1
println(steps)        // 111

Scala 3 removed do { ... } while (cond). Write it with an explicit while true and break-style logic, or restructure with recursion. Since there is no break keyword either, loops that need early exit are usually written with find, takeWhile or exists:

SCALA
val firstBig = (1 to 100).find(n => n * n > 200)   // Some(15)

If you truly need break, scala.util.boundary provides one in Scala 3:

SCALA
import scala.util.boundary, boundary.break

val index = boundary:
  for i <- 0 until 100 do
    if i * i > 50 then break(i)
  -1

Here index is 8.

foreach vs for

These do the same thing:

SCALA
List(1, 2, 3).foreach(println)
for n <- List(1, 2, 3) do println(n)

Pick the one that reads better. Use foreach for a single function, for when you have guards or several steps.

Common mistakes

  • Using yield with side effects. The body should compute a value.
  • Worrying that 1 to 1000000 allocates a million numbers. A Range stores only start, end and step.
  • Using a var accumulator in a for when sum, map or foldLeft would be clearer.
  • Forgetting that the last generator in a nested for varies fastest.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 1 until 4 produce?

    until excludes the end value, to includes it.
  2. 2. What does adding yield change in a for?

    for ... yield is a comprehension that builds a result from each iteration.
  3. 3. A for with several generators is translated into which methods?

    Nested generators use flatMap, the last one map, guards use withFilter, and loops without yield use foreach.
  4. 4. In a for over Option values, what happens if one value is None?

    Option's flatMap short-circuits, so one None makes the whole comprehension None.

Summary

  • for x <- xs do ... loops; for x <- xs yield ... builds a new collection.
  • Ranges: to includes the end, until excludes it, by sets the step.
  • Guards (if) and definitions (=) can sit between generators.
  • for desugars to foreach, map, flatMap and withFilter, so it works with Option, Future and more.
  • Scala has no break keyword; use find, takeWhile or scala.util.boundary.

Next: Methods and Functions