Scala does not have a built-in break statement. In the simple function-based tutorials here, we can stop the loop by returning from the current function.
When Scala reaches the return statement, it exits the function immediately, so the loop stops too.
Breaking a for loop:
In this example, we will terminate the loop when we find a "banana" in our array:
val fruits = Array("kivi", "orange", "banana", "apple", "pear")
for (fruit <- fruits) {
println(fruit)
if(fruit == "banana") {
return
}
}
The output of this code is:
kivi
orange
banana
As you can see, our program doesn't print apple and pear.
Here's what happens during this loop:
1. First iteration:
a. fruit = "kivi"
b. println(fruit); => Output: kivi
c. Is fruit == "banana"? No.
2. Second iteration:
a. fruit = "orange"
b. println(fruit); => Output: orange
c. Is fruit == "banana"? No.
3. Third iteration:
a. fruit = "banana"
b. println(fruit); => Output: banana
c. Is fruit == "banana"? Yes:
return => Exit the function immediately
Here's the same program but iterating through the array with indices instead:
val fruits = Array("kivi", "orange", "banana", "apple", "pear")
for (i <- fruits.indices) {
println("Index " + i + ": " + fruits(i))
if(fruits(i) == "banana") {
return
}
}
The output of this code is:
Index 0: kivi
Index 1: orange
Index 2: banana
As you can see, our program doesn't print apple and pear.
Assignment
Let's print all the lessons our student finished!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.