1
votes
// iteratorFunc is Iterable[SomeClass]
val iterator1 = iteratorFunc.iterator

iterator1 foreach {
    ...
}


val iterator2 = iteratorFunc.iterator

iterator2 foreach {
   ...
}

The code inside iterator1 foreach is successfully done. But, iterator2 gives empty iterator.

Please help.

2
What is the type of iteratorFunc? You say Iterable, but I suspect that its iterator method is broken. Is it possible that iterator1 eq iterator2? Because then obviously there is the bug. Iterators are consume-once only.0__
@0__ you should write an answer for it, I think it's a bug of iteratorFunc, too.cloud

2 Answers

8
votes

You should duplicate it.

val (iterator1, iterator2) = iteratorFunc.iterator.duplicate
-1
votes

Well, using duplicate() is super expensive, because the next() function is synchronized. Also you need to cache the difference between these two iterators.