LowFieldTheory
LowFieldTheory

Reputation: 1773

Bug in Scala 2.10, Iterator.size?

Is this normal?

scala> val x = Iterator(List[String]("str"))
lol: Iterator[List[String]] = non-empty iterator

scala> x.size
res1: Int = 1

scala> x.size
res2: Int = 0

And actually I'm meeting other weird errors.. a possible bug?

Upvotes: 9

Views: 4975

Answers (2)

Marius Danila
Marius Danila

Reputation: 10401

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

Upvotes: 25

ziggystar
ziggystar

Reputation: 28670

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.

Upvotes: 8

Related Questions