I’m confused about behavior of method take in trait Iterator. It seems that it doesn’t consume items. Here is an example:
scala> Iterator(1,2,3)
res0: Iterator[Int] = non-empty iterator
scala> res0 take 2 toArray
res1: Array[Int] = Array(1, 2)
scala> res0.next
res2: Int = 1
Apparently step 2 consumes two items, but in step 3 the Iterator is still at first item. Looking at the implementation, I can’t see any kind of copying or buffering, just a new Iterator which delegates to the underlying one. How could it be possible? How can I manage to really consume n items?
The iterator in question is defined in
IndexedSeqLike#Elements(source). A ticket was recently filed about the the inconsistent behaviour oftakeacross different iterator implementations.To really consume N items, call
Iterator#nextN times.You might want to consider using
Stream, which is a lazy (likeIterator), but is also immutable (unlikeIterator).