Bug in Scala 2.10, Iterator.size?

No it's not a bug. It's the normal behavior.

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.

When you ask it to give you the size 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.

To understand better what's happening, you can do this:

val it = Iterator(1, 2, 3, 4)
//it: >1 2 3 4
it.next() //ask for the next element
//it: 1 >2 3 4
it.next()
//it: 1 2 >3 4
println(it.size) // prints 2
//it: 1 2 3 4 >
println(it.size) // prints 0

It's normal. To find out the size of an Iterator, you have to iterate through it until it is empty.

And then it's empty (size == 0).

Iterators are to be used with care, since they are very fragile data-structures.

Tags:

Iterator

Scala