Reputation: 1146
I am trying to learn Scala through a sample project that I have. In it there is a variable record defined as:
val records: Iterator[Product2[K, V]]
It is passed around in different methods. I explore its contents using :
records.foreach(println)
However, when I try to print the contents using this iterator again, even in successive lines of code, I get no results. It seems as if the iterator is consumed. How do prevent it from happening and be able to explore the contents of the iterator without rendering it useless for the rest of the code?
Upvotes: 1
Views: 284
Reputation: 14404
An Iterator
extends TraversableOnce
and hence can only be iterated over once, as it represents a mutating pointer into an Iterable
. If you want something that can be traversable repeatedly and without affecting multiple, parallel accesses, you need to use the Iterable
instead, which extends Traversable
and on foreach
creates a new Iterator
for that specific context
Upvotes: 8