• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A very strange error with Scala Iterator

 
Joe Harry
Ranch Hand
Posts: 10047
3
Eclipse IDE Mac PPC Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How could the code below print?

 
Maxim Karvonen
Ranch Hand
Posts: 120
12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Joe.

A length method may consume all content of the iterator. Most probably, your particular implementation takes items from the iterator and just counts them. There is a note in the scaladoc for the length method:
Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.


This behaviour is exposed by many other methods (like sum, max, etc...). All that methods will consume content of the iterator. I believe it (undefined behaviour after some "aggregate" method) applies not only to Iterator, but to any instance of TraversableOnce (from which Iterator extends).

To fix you problem you should first store items in some collection (list will be fine because you need it later) and then use that collection.
 
Joe Harry
Ranch Hand
Posts: 10047
3
Eclipse IDE Mac PPC Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. that makes sense to me. I've found an alternative way to get rid of that error. But good to know the root cause!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic