Scala Loops & for-Expressions
Scala has a while loop for classic imperative code and a very flexible for construct. A for loop with do runs code for each element; a for with yield is an expression that builds a new collection. In everyday Scala you will often skip loops entirely in favour of collection methods like map and foreach.
for … do
@main def run(): Unit =
for i <- 1 to 3 do
println(s"Round $i")
val fruits = List("apple", "pear", "fig")
for fruit <- fruits do
println(fruit.toUpperCase)Round 1
Round 2
Round 3
APPLE
PEAR
FIG
i <- 1 to 3 is a generator: it takes each value from the range in turn. 1 to 3 includes 3; 1 until 3 stops before it.
Several generators and guards
Multiple generators produce nested loops. An if inside the for header is a guard that skips unwanted combinations.
@main def run(): Unit =
for
row <- 1 to 3
col <- 1 to 3
if row != col
do
print(s"($row,$col) ")
println()(1,2) (1,3) (2,1) (2,3) (3,1) (3,2)
for … yield: building collections
With yield, the for expression collects one result per iteration into a new collection of the same kind as the first generator.
@main def run(): Unit =
val squares = for n <- List(1, 2, 3, 4) yield n * n
println(squares)
val pairs =
for
size <- List("S", "M")
color <- List("red", "blue")
yield s"$size-$color"
println(pairs)
val evensDoubled = for n <- 1 to 10 if n % 2 == 0 yield n * 2
println(evensDoubled)List(1, 4, 9, 16)
List(S-red, S-blue, M-red, M-blue)
Vector(4, 8, 12, 16, 20)
A range yields a Vector. Under the hood, for … yield is translated into calls to map, flatMap and withFilter — which is why it also works with Option, Either, Future and more.
while loops
while repeats as long as its condition is true. It needs a var, so it is mainly used for low-level or performance-critical code.
@main def run(): Unit =
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(s"Collatz steps for 27: $steps")Collatz steps for 27: 111
Note: Scala 3 removed
do … while. If you need the body to run at least once, usewhile ({ body; condition }) ()or, better, restructure the logic.
break and continue
Scala has no break or continue keywords. Usually you don't need them:
| You want to… | Idiomatic Scala |
|---|---|
skip some elements (continue) |
a guard: for x <- xs if x > 0 do … or filter |
stop at the first match (break) |
find, exists, takeWhile, indexWhere |
| stop early with a result | a recursive function, or boundary/break from scala.util |
import scala.util.boundary, boundary.break
@main def run(): Unit =
val readings = List(12, 15, 9, -1, 20)
println(readings.takeWhile(_ >= 0))
println(readings.find(_ < 10))
val firstNegative = boundary:
for (r, i) <- readings.zipWithIndex do
if r < 0 then break(i)
-1
println(s"First negative at index $firstNegative")List(12, 15, 9)
Some(9)
First negative at index 3
foreach and zipWithIndex
For simple "do something with each element" work, foreach is the most direct option. Need the index too? Pair elements with zipWithIndex.
@main def run(): Unit =
val tasks = List("write", "test", "ship")
tasks.foreach(println)
for (task, i) <- tasks.zipWithIndex do
println(s"${i + 1}. $task")write
test
ship
1. write
2. test
3. ship
Test yourself
What does for n <- List(1, 2, 3) yield n * 10 return?
()List(10, 20, 30)60Vector(10, 20, 30)
Which range contains the numbers 1, 2 and 3 but not 4?
1 until 31 to 41 to 30 to 3
How do you skip elements inside a for without a continue keyword?
- Use
skip - Add a guard such as
if x > 0to the generator - Throw an exception
- It is impossible