🎓 A1Learner
🔍
0 of 48 lessons completed

Scala Iterators

An iterator is a one-pass walk through a collection, one item at a time. It hands out each item once and then moves on.

Next hands out items one at a time

The first next call gives 10, and hasNext is still true because items remain. The next call gives 20.

@main def main(): Unit =
  val it = List(10, 20, 30).iterator
  println(it.next())
  println(it.hasNext)
  println(it.next())

Take leaves the rest of the walk waiting

Taking two items consumes only the first two. The iterator still has items left, and the next item is 3.

@main def main(): Unit =
  val it = List(1, 2, 3, 4).iterator
  val firstTwo = it.take(2).toList
  println(firstTwo)
  println(it.hasNext)
  println(it.next())

Filter and map build a new one-pass walk

The filter keeps only even numbers, and the map multiplies each kept number by 10. Forcing with toList runs the whole walk once.

@main def main(): Unit =
  val result = List(1, 2, 3, 4).iterator.filter(_ % 2 == 0).map(_ * 10).toList
  println(result)

Example

@main def main(): Unit =
  val it = List(5, 10, 15).iterator
  var total = 0
  while it.hasNext do total += it.next()
  println(total)
  println(it.hasNext)

Key points

  • Next: next hands out the current item and moves the iterator forward.
  • HasNext: hasNext tells you whether another item is left.
  • One-pass: an iterator can only be walked once, so each item is given out a single time.
  • Take: take on an iterator hands out only the first few items and leaves the rest waiting.
  • Transform: filter and map on an iterator build a new one-pass walk.

In this example, the while loop keeps asking for the next item while one remains, and adds each item to the total. After the last item, hasNext is false, which proves the walk is spent and cannot be walked again.

Note

printing an iterator shows an address, not its items, so print its items instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

An iterator over List(1, 2, 3) has already handed out 1 and 2. What does next() give now?