Loops in Scala
In this lesson, you will learn about loops in Scala. Loops allow you to execute a block of code multiple times until a condition is met.
Loops are essential when working with collections, performing repetitive tasks, and automating processes in programs.
Why Loops Are Important
Loops help you avoid writing the same code again and again. They are commonly used for:
- Iterating over lists and arrays
- Processing large amounts of data
- Repeating tasks until a condition is satisfied
- Building scalable logic
The for Loop
The for loop is the most commonly used loop in Scala.
It iterates over a range or collection.
for (i <- 1 to 5) {
println(i)
}
This loop prints numbers from 1 to 5.
The expression 1 to 5 creates a range.
Using until in for Loop
The until keyword creates a range that excludes the last value.
for (i <- 1 until 5) {
println(i)
}
This prints numbers from 1 to 4.
Looping Through Collections
Scala loops are commonly used with collections like lists.
val fruits = List("Apple", "Banana", "Orange")
for (fruit <- fruits) {
println(fruit)
}
Each element of the list is accessed one by one.
for Loop with Conditions (Guards)
Scala allows you to add conditions inside loops using guards.
for (i <- 1 to 10 if i % 2 == 0) {
println(i)
}
This prints only even numbers between 1 and 10.
Nested for Loops
You can nest loops to handle multi-level iterations.
for (i <- 1 to 3) {
for (j <- 1 to 2) {
println(s"i = $i, j = $j")
}
}
Nested loops are useful for matrix operations and combinations.
for Loop as an Expression
In Scala, a for loop can also return a value.
This is done using yield.
val squares = for (i <- 1 to 5) yield i * i
println(squares)
This creates a new collection containing the squares of numbers.
The while Loop
The while loop runs as long as a condition is true.
var count = 1
while (count <= 5) {
println(count)
count += 1
}
Use while loops carefully, as they rely on mutable variables.
The do–while Loop
The do–while loop executes the block at least once.
var num = 1
do {
println(num)
num += 1
} while (num <= 3)
Even if the condition is false, the loop runs once.
Best Practices for Loops
- Prefer
forloops overwhile - Use
yieldfor transformations - Avoid deeply nested loops when possible
- Use immutable collections when looping
📝 Practice Exercises
Exercise 1
Print numbers from 1 to 10 using a for loop.
Exercise 2
Print only odd numbers between 1 and 10.
Exercise 3
Create a list of cubes for numbers 1 to 5.
✅ Practice Answers
Answer 1
for (i <- 1 to 10) {
println(i)
}
Answer 2
for (i <- 1 to 10 if i % 2 != 0) {
println(i)
}
Answer 3
val cubes = for (i <- 1 to 5) yield i * i * i
println(cubes)
What’s Next?
In the next lesson, you will learn about Functions in Scala, which help you organize and reuse logic efficiently.