Scala:Scala 集合中的 Traversable 和 Iterable trait 有什么区别?

Scala:Scala 集合中的 Traversable 和 Iterable trait 有什么区别?

问题描述:

我看过this question 但仍然不明白 Iterable 和 Traversable 特征之间的区别.谁能解释一下?

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

简单来说,迭代器保持状态,遍历器不保持.

To put it simply, iterators keep state, traversables don't.

Traversable 有一个抽象方法:foreach.当您调用 foreach 时,集合 会将其保留的所有元素一个接一个地提供给传递的函数.

A Traversable has one abstract method: foreach. When you call foreach, the collection will feed the passed function all the elements it keeps, one after the other.

另一方面,Iterable 具有抽象方法 iterator,它返回一个 Iterator.您可以在 Iterator 上调用 next 以在您选择的时间获取下一个元素.在您这样做之前,它必须跟踪它在集合中的位置,以及接下来要做什么.

On the other hand, an Iterable has as abstract method iterator, which returns an Iterator. You can call next on an Iterator to get the next element at the time of your choosing. Until you do, it has to keep track of where it was in the collection, and what's next.