What is the difference between Iterator and Iterable in scala?
I thought that Iterable represents a set that I can iterate through, and Iterator is a “pointer” to one of the items in the iterable set.
However, Iterator has functions like forEach, map, foldLeft. It can be converted to Iterable via toIterable. And, for example, scala.io.Source.getLines returns Iterator, not Iterable.
But I cannot do groupBy on Iterator and I can do it on Iterable.
So, what’s the relation between those two, Iterator and Iterable?
In short: An
Iteratordoes have state, whereas anIterabledoes not.See the API docs for both.
Iterable:
Iterator:
With an
Iteratoryou can stop an iteration and continue it later if you want. If you try to do this with anIterableit will begin from the head again:Note, that I didn’t use
takeonIterator. The reason for this is that it is tricky to use.hasNextandnextare the only two methods that are guaranteed to work as expected onIterator. See the Scaladoc again: