Search code examples
scalaiterator

Scala Iterator next called after size does not raise error


Using local interpreter of Scala 2.13.10 I am running the following code

scala> val it = Iterator("a", "number", "of", "words")
val it: Iterator[String] = <iterator>
scala> it.size
val res0: Int = 4
scala> it.next()
val res14: String = a

I was under the assumption that running the command it.size will traverse the iterator, and it.next() will fail, as it noted in the Scala documentation

it.size The number of elements returned by it. Note: it will be at its end after this operation!

https://docs.scala-lang.org/overviews/collections-2.13/iterators.html

What I am missing here?


Solution

  • The overview doesn't fully describe the behavior of size. For iterators where knownSize is nonnegative (as in those created from a finite collection), size does not in fact traverse the iterator.

    That said, size is one of the methods on Iterator where the only safe thing to do after calling it is to not use the iterator again (nearly every method on Iterator that's not hasNext or next is such a method).