Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

2.6 Advanced for Loops and for Comprehensions

In the preceding section, you saw the basic form of the for loop. However, this construct is much richer in Scala than in Java or C++. This section covers the advanced features.

You can have multiple generators of the form variable <- expression. Separate them by semicolons. For example,

for (i <- 1 to 3; j <- 1 to 3) print((10 * i + j) + " ")
   // Prints 11 12 13 21 22 23 31 32 33

Each generator can have a guard, a Boolean condition preceded by if:

for (i <- 1 to 3; j <- 1 to 3 if i != j) print((10 * i + j) + " ")
  // Prints 12 13 21 23 31 32

Note that there is no semicolon before the if.

You can have any number of definitions, introducing variables that can be used inside the loop:

for (i <- 1 to 3; from = 4 - i; j <- from to 3) print((10 * i + j) + " ")
  // Prints 13 22 23 31 32 33

When the body of the for loop starts with yield, then the loop constructs a collection of values, one for each iteration:

for (i <- 1 to 10) yield i % 3
  // Yields Vector(1, 2, 0, 1, 2, 0, 1, 2, 0, 1)

This type of loop is called a for comprehension.

The generated collection is compatible with the first generator.

for (c <- "Hello"; i <- 0 to 1) yield (c + i).toChar
  // Yields "HIeflmlmop"
for (i <- 0 to 1; c <- "Hello") yield (c + i).toChar
  // Yields Vector('H', 'e', 'l', 'l', 'o', 'I', 'f', 'm', 'm', 'p')
  • + Share This
  • 🔖 Save To Your Account