Bug in Scala 2.10, Iterator.size?

回眸只為那壹抹淺笑 提交于 2020-06-25 09:45:09

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/19458066/bug-in-scala-2-10-iterator-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!