Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug in Scala 2.10, Iterator.size?

Tags:

iterator

scala

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?

like image 535
LowFieldTheory Avatar asked Oct 18 '13 19:10

LowFieldTheory


2 Answers

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
like image 192
Marius Danila Avatar answered Oct 23 '22 19:10

Marius Danila


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.

like image 29
ziggystar Avatar answered Oct 23 '22 17:10

ziggystar