Scala — Skipping iterations with for guards
A Scala for guard accepts only elements that satisfy its Boolean condition. It expresses the usual continue-on-invalid rule directly in the traversal.
A simple example
Print only matching numbers
- Start with 1, 2, 3
- Do this Keep numbers other than 2
- Result 1 → 3
object Lesson extends App {
for (n <- 1 to 3 if n != 2) {
println(n)
}
}
1 3
Exclude invalid readings while keeping zero
Skip negative readings, which represent invalid measurements here. Count every valid reading, including zero, and add it to the total. The guard runs before the loop body. Valid zeroes contribute to the count and add zero to the sum.
A counter records visitors in each time interval. A negative reading signals a fault, while zero means the counter worked and nobody entered. Keeping 0, 4 and 6 gives three valid intervals and ten visitors.
Run the example
Use Scala 2.13. Run these commands from the directory containing the example.
scalac Lesson.scala
scala Lesson
object Lesson {
def main(args: Array[String]): Unit = {
var count = 0
var sum = 0
for (reading <- List(-2, 0, 4, -1, 6) if reading >= 0) {
count += 1
sum += reading
}
println(s"$count readings, sum $sum")
}
}
3 readings, sum 10
The valid values are 0, 4, and 6. Skipping the negative entries changes the count without losing the measured zero.
Try it yourself
Append −3 and then 0. What should the count and sum become?
Check your answer
The count rises to 4 and the sum stays 10. Only the appended zero is a valid measurement.