Learn Scala 3 Fast: Constructs: for Expressions With Multiple Generators

Backtracking for a moment, here’s another for loop in the REPL:

scala> for i <- 1 to 3 do println(i)

In that example, this portion of the code is known as a generator, because it generates the numbers 1 through 3:

i <- 1 to 3

Similarly, in this code:

val ints = List(1, 2, 3)
for i <- ints do println(i)

this portion of the code is also a generator:

i <- ints

I mention this for two reasons. First, it’s a piece of technical goo you’ll need to know when talking to other Scala developers. Second, for loops and expressions can have multiple generators:

val ints = List(1, 2)
val chars = List('a', 'b')

    i <- ints
    c <- chars
    println(s"i = $i, c = $c")

That for loop results in this output:

i = 1, c = a
i = 1, c = b
i = 2, c = a
i = 2, c = b

As with other programming languages it’s possible to nest one for loop inside another, but in Scala this isn’t necessary, and as you’ll see in the lessons that follow, there are other benefits to this “generator” approach.


The exercises for this lesson are available here.

books by alvin