This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Scala and the fly likes A very strange error with Scala Iterator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Languages » Scala
Bookmark "A very strange error with Scala Iterator" Watch "A very strange error with Scala Iterator" New topic
Author

A very strange error with Scala Iterator

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9344
    
    2

How could the code below print?



SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Maxim Karvonen
Ranch Hand

Joined: Jun 14, 2013
Posts: 101
    
  10
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

Joined: Sep 26, 2006
Posts: 9344
    
    2

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
 
subject: A very strange error with Scala Iterator
 
Similar Threads
Printing a HashSet that contains arrays of Strings
Need help with code!!!
How do I covert on object into string
How can I get the values out of a Map and assign them each to their own String?(SOLVED)
Struts OGNL how to acces vector elements