- 2.1 Conditional Expressions
- 2.2 Statement Termination
- 2.3 Block Expressions and Assignments
- 2.4 Input and Output
- 2.5 Loops
- 2.6 Advanced for Loops and for Comprehensions
- 2.7 Functions
- 2.8 Default and Named Arguments L1
- 2.9 Variable Arguments L1
- 2.10 Procedures
- 2.11 Lazy Values L1
- 2.12 Exceptions
- Exercises
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')