Scala For Loop
The for loop in Scala iterates over a range, collection, or any sequence of values. Scala's for loop is more versatile than those in most languages — it also forms the basis of for comprehensions, which are a powerful functional programming tool covered in the next topic.
Basic For Loop over a Range
for i <- 1 to 5 do
println(i)
// 1
// 2
// 3
// 4
// 5
The <- symbol (called a "generator") means "for each value i drawn from the range 1 to 5." The range 1 to 5 is inclusive — it includes 5.
Exclusive Range with until
for i <- 1 until 5 do
println(i)
// 1
// 2
// 3
// 4 ← stops before 5
1 to 5 → 1, 2, 3, 4, 5 (includes 5)
1 until 5 → 1, 2, 3, 4 (excludes 5)
Step in a Range
for i <- 1 to 10 by 2 do
print(s"$i ")
// 1 3 5 7 9
for i <- 10 to 1 by -1 do
print(s"$i ")
// 10 9 8 7 6 5 4 3 2 1
Iterating Over a Collection
val fruits = List("Apple", "Mango", "Banana", "Grapes")
for fruit <- fruits do
println(s"I like $fruit")
// I like Apple
// I like Mango
// I like Banana
// I like Grapes
For Loop with Arrays and Maps
val scores = Array(88, 92, 75, 100, 63)
for score <- scores do
println(if score >= 90 then s"$score — Excellent" else s"$score — Good")
val capitals = Map("India" -> "New Delhi", "Japan" -> "Tokyo", "France" -> "Paris")
for (country, capital) <- capitals do
println(s"$country: $capital")
// India: New Delhi
// Japan: Tokyo
// France: Paris
Guards (Filtering Inside a For)
Add if conditions inside the for loop to skip certain values:
for i <- 1 to 20 if i % 3 == 0 do
print(s"$i ")
// 3 6 9 12 15 18
for word <- List("cat", "elephant", "ox", "hippopotamus") if word.length > 3 do
println(word)
// elephant
// hippopotamus
Nested For Loops
for row <- 1 to 3 do
for col <- 1 to 3 do
print(f"${row * col}%3d")
println()
// 1 2 3
// 2 4 6
// 3 6 9
Scala lets you combine multiple generators in a single for — this is cleaner than nesting:
for
row <- 1 to 3
col <- 1 to 3
do
print(f"${row * col}%3d")
if col == 3 then println()
// 1 2 3
// 2 4 6
// 3 6 9
Multiple Generators with Guards
// All pairs (i, j) where i + j == 10
for
i <- 1 to 9
j <- 1 to 9
if i + j == 10
do
println(s"($i, $j)")
// (1, 9)
// (2, 8)
// (3, 7)
// (4, 6)
// (5, 5)
// (6, 4)
// (7, 3)
// (8, 2)
// (9, 1)
Defining Values Inside a For
val people = List(("Alice", 28), ("Bob", 35), ("Carol", 22))
for
(name, age) <- people
yearsToRetirement = 60 - age
if yearsToRetirement > 20
do
println(s"$name retires in $yearsToRetirement years")
// Alice retires in 32 years
// Carol retires in 38 years
Iterating with Index
Use zipWithIndex to get both the element and its position:
val colors = List("Red", "Green", "Blue")
for (color, index) <- colors.zipWithIndex do
println(s"${index + 1}. $color")
// 1. Red
// 2. Green
// 3. Blue
For Loop vs foreach vs map
val numbers = List(1, 2, 3, 4, 5)
// For loop — side effects (printing)
for n <- numbers do print(s"$n ")
// foreach — equivalent to for loop
numbers.foreach(n => print(s"$n "))
// map — produces a new collection (covered in comprehensions)
val doubled = numbers.map(_ * 2) // List(2, 4, 6, 8, 10)
Use for loop when: Use map/filter when:
────────────────── ─────────────────────────
Side effects only Producing a new collection
Printing results Transforming data
Logging Filtering elements
Mixed operations Chaining transformations
String Characters
val word = "Scala"
for ch <- word do
print(s"$ch-")
// S-c-a-l-a-
Practical Example: Multiplication Table
val n = 7
println(s"Multiplication Table for $n")
println("-" * 20)
for i <- 1 to 10 do
println(f"$n%2d × $i%2d = ${n * i}%3d")
// Multiplication Table for 7
// --------------------
// 7 × 1 = 7
// 7 × 2 = 14
// ...
// 7 × 10 = 70
Scala 2 Style for Reference
// Scala 2 (also valid in Scala 3)
for (i <- 1 to 5) {
println(i)
}
// With guard
for (i <- 1 to 10 if i % 2 == 0) {
println(i)
}
The Scala 3 style uses do and indentation instead of parentheses and braces. Both compile to identical bytecode. New projects should use the Scala 3 style for cleaner, more readable code.
