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
- Start with 1, 2, 3, 4
- Do this Keep values below 3
- Result 1 → 2
object Lesson extends App {
(1 to 4).takeWhile(n => n < 3).foreach(println)
}
1 2
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.
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
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)
}
}
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.