Lesson contents

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

  1. Start with 1, 2, 3
  2. Do this Keep numbers other than 2
  3. Result 1 → 3
The guard checks each number. It keeps 1 and 3 and skips 2.
Lesson.scala
object Lesson extends App {
    for (n <- 1 to 3 if n != 2) {
        println(n)
    }
}
Output
1
3
Advertisements

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.

Valid intervals: 0, 4, 6. Intervals counted: 3. Total visitors: 10.
Count the quiet interval too

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
Lesson.scala
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")
  }
}
Output
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.

Scala language specification

Related tags

  • Scala
  • continue
  • filtering
  • loop control