TraversableOnce: "A template trait for collections which can be traversed either once only or one or more times."
I don't understand this sentence. Why can be traversed more times? Isn't only once? Thank you!
Note that with Scala 2.13 (June 2019), there is no more Traversable
and TraversableOnce
: They remain only as deprecated aliases for Iterable
and IterableOnce
. (initially part of the Collections rework)
IterableOnce
also has the same sentence:
A template trait for collections which can be traversed either once only or one or more times.
This time:
The goal is to provide a minimal interface without any sequential operations.
This allows third-party extension like Scala parallel collections to integrate at the level ofIterableOnce
without inheriting unwanted implementations.
The Scaladoc also says
This trait exists primarily to eliminate code duplication between Iterator and Traversable, and thus implements some of the common methods that can be implemented solely in terms of
foreach
without access to a Builder.
Iterators can only be 'traversed' once. A Traversable can be traversed many times.
Essentially, TraversableOnce is an interface that abstracts away how you handle Iterators and Traversables. Your code could receive either an Iterator or a Traversable and handle them in exactly the same way!
For a good explanation of many of the traits used in the Collections library, I believe the majority (if not all) of the Scala 2.8 Collections Design Tutorial is still correct.
Because there are something can only be traversed once, eg:
Iterator.continually(readline)
The expression will create an iterator, but it can be only traversed once, otherwise it must store all read data, which is a waste in most of the time.
And many container can be traversed as many times as you want, like Array
, Map
and so on
If a Traversable can be traversed more than once, it sure can be traversed once. So all Traversable are also TraversableOnce, TraversableOnce can be traversed at lease once, but also can be more times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With