Scala does not have a built-in continue statement. The usual approach is to put the work inside an if statement, so the work only runs for the items we want to keep.
This gives the same behavior as skipping the current iteration.
In this example, we will not let anyone inside a bar if their age is less than 21:
val ages = Array(10, 30, 21, 19, 25)
for (age <- ages) {
if (age >= 21) {
println("Someone of age " + age + " entered the bar.")
}
}
The output of this program is:
Someone of age 30 entered the bar.
Someone of age 21 entered the bar.
Someone of age 25 entered the bar.
As you can see, our program doesn't print for ages 10 and 19.
Here's what happens during this loop:
1. First iteration:
a. age = 10
b. Is age >= 21? No, so nothing is printed.
2. Second iteration:
a. age = 30
b. Is age >= 21? Yes.
c. println
3. Third iteration:
a. age = 21
b. Is age >= 21? Yes.
c. println
4. Forth iteration:
a. age = 19
b. Is age >= 21? No, so nothing is printed.
5. Fifth iteration:
a. age = 25
b. Is age >= 21? Yes.
c. println
Assignment
Let's allow only the people with height at least 170 into the arena.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.