Lesson contents

Scala — Traversing input with iterators

A Scala iterator processes values as they are consumed. takeWhile can stop at the first end marker, then filter selects which earlier readings contribute to the sum.

A simple example

Stop at the first failed test

  1. Start with 1, 2, 3, 4
  2. Do this Keep values below 3
  3. Result 1 → 2
takeWhile stops as soon as 3 fails the test. Each retained number is printed on its own line.
Lesson.scala
object Lesson extends App {
    (1 to 4).takeWhile(n => n < 3).foreach(println)
}
Output
1
2
Advertisements

Stop at the end of a batch

takeWhile ends the iterator at the sentinel. filter then removes negative readings, and sum consumes the iterator. Reversing the order with a filter that removes zero would lose the stopping signal.

Readings: 4, −1, 0, 7. End marker: 0. This batch totals: 4.
Find the end of a scanner batch

A scanner sends 4, then an invalid reading of −1, then the batch marker 0. Add 4, skip the invalid reading and stop at the marker. The later 7 belongs to the next batch.

Run the example

Scala 2.13 with JDK 11 or later. Run these commands from the directory containing the example.

scalac Lesson.scala
scala Lesson
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
    val readings = List(4, -1, 0, 7)
    val accepted = readings.iterator.takeWhile(_ != 0).filter(_ > 0)
    println(accepted.sum)
  }
}
Output
4

Start the total at zero. Add 4, skip −1, and stop at 0. The final 7 belongs to a different batch, so the result is 4.

Try it yourself

What changes if the input is 4, −1, 7, 0?

Check your answer

Both positive readings arrive before the sentinel. Their sum is 11. An empty sequence yields 0.

Tour of Scala

Related tags

  • Scala
  • iteration
  • loop control
  • accumulators