Behavior of the Iterator size method in Scala


Iterators are a useful structure to iterate over collections (List, Set, Seq, Map, etc) and access their elements one by one. Two important methods in Scala Iterator are next() and hasNext.

  • hasNext: Indicates if there is another element to return
  • next(): Returns that element.

Iterators are mutable things. You can think of them as pointers. Each time you ask an iterator to give you the next element it points to it will move one position further.


Behavior of the size method

When the size of a iterator is requested, it will traverse each element in the sequence it points to, moving each time one position to the right. When it has no more elements to traverse iterator.hasNext == false it will return the size. But by then it will have exhausted all the elements.

When a new call to size is made, the iterator is already positioned at the end, so it will immediately return 0. Therefore if you tries to iterate your iterator after getting the size of it, you will notice the iterator is not doing anything.

val list = scala.collection.immutable.List(1, 2, 3)
val iterator = list.iterator
println(iterator.size) // 3
println(iterator.hasNext) // false
println(iterator.size) // 0



Leave a Reply

Your email address will not be published.