What is the relation between Iterable and Iterator?

后端 未结 2 1175
耶瑟儿~
耶瑟儿~ 2021-01-31 07:44

What is the difference between Iterator and Iterable in scala?

I thought that Iterable represents a set that I can iterate through

2条回答
  •  渐次进展
    2021-01-31 08:11

    Another explanation from Martin Odersky and Lex Spoon:

    There's an important difference between the foreach method on iterators and the same method on traversable collections: When called to an iterator, foreach will leave the iterator at its end when it is done. So calling next again on the same iterator will fail with a NoSuchElementException. By contrast, when called on on a collection, foreach leaves the number of elements in the collection unchanged (unless the passed function adds to removes elements, but this is discouraged, because it may lead to surprising results).

    Source: http://www.scala-lang.org/docu/files/collections-api/collections_43.html

    Note also (thanks to Wei-Ching Lin for this tip) Iterator extends the TraversableOnce trait while Iterable doesn't.

提交回复
热议问题