for Loops
At the end of the week, the logbook prints one line per run for Asha to check. Repeating an action for every element of a collection is the most common loop there is, and Scala's for says it in one line.
The rule
for x <- items do action: once per element, in order.
val runs = List(5.0, 8.5, 3.2, 10.0)
for km <- runs do
println(s"Logged $km km")km <- runsis a generator. Read the arrow as "taken from": each time round,kmis the next element.dointroduces the body, which can be one line or an indented block.- The loop runs once per element, in the collection's order, and the whole
for … doproducesUnit. It is used for its effects, such as printing.
A guard skips elements that fail a test:
for km <- runs if km >= 8 do
println(s"Long run: $km km") // 8.5, then 10.0Two generators on one line loop over every combination, with the first generator changing slowest:
for name <- List("Asha", "Ben"); day <- List("Sat", "Sun") do
println(s"$name runs on $day")
// Asha runs on Sat, Asha runs on Sun, Ben runs on Sat, Ben runs on SunA Map's pairs can be taken apart right in the generator: for (name, km) <- weekKm do ….
The Scala 2 style, which still compiles, wraps the generator in parentheses and has no do: for (km <- runs) println(km). The same loop can also be written as a method call, runs.foreach(km => println(km)).
The shortcut
Read a for aloud: "for each km taken from runs, if km is at least 8, do this." With two generators, picture a clock: the second generator is the minute hand, and it goes all the way round before the first one moves on.
First name, first day
name is Asha and day is Sat. Print "Asha runs on Sat".
Drills
Answer fast — trust the rule.
What does for km <- runs if km >= 8 do println(km) print for List(5.0, 8.5, 3.2, 10.0)?
How many lines does for a <- List("Asha", "Ben"); d <- List("Sat", "Sun") do println(a + d) print?
In that same loop, what is the second line printed?
What does a for … do loop produce as a value?
Which is the Scala 2 style of the same loop, still accepted by Scala 3?
Remember
for x <- items do …runs once per element, in order, and returns Unit.- Read it aloud; with two generators, the second moves fastest, like a minute hand.
- Trap: expecting a
for … doto return a collection — it only has effects.
