Scala: What is the difference between Traversable and Iterable traits in Scala collections?

后端 未结 4 1207
迷失自我
迷失自我 2020-12-04 09:05

I have looked at this question but still don\'t understand the difference between Iterable and Traversable traits. Can someone explain ?

4条回答
  •  日久生厌
    2020-12-04 09:35

    Daniel's answer sounds good. Let me see if I can to put it in my own words.

    So an Iterable can give you an iterator, that lets you traverse the elements one at a time (using next()), and stop and go as you please. To do that the iterator needs to keep an internal "pointer" to the element's position. But a Traversable gives you the method, foreach, to traverse all elements at once without stopping.

    Something like Range(1, 10) needs to have only 2 integers as state as a Traversable. But Range(1, 10) as an Iterable gives you an iterator which needs to use 3 integers for state, one of which is an index.

    Considering that Traversable also offers foldLeft, foldRight, its foreach needs to traverse the elements in a known and fixed order. Therefore it's possible to implement an iterator for a Traversable. E.g. def iterator = toList.iterator

提交回复
热议问题