Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: what is trait TraversableOnce? What's the different between TraversableOnce and Traversable?

Tags:

scala

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!

like image 224
Guo Avatar asked Dec 31 '15 08:12

Guo


3 Answers

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 of IterableOnce without inheriting unwanted implementations.

like image 89
VonC Avatar answered Nov 17 '22 19:11

VonC


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.

like image 25
colinjwebb Avatar answered Nov 17 '22 18:11

colinjwebb


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.

like image 1
Zang MingJie Avatar answered Nov 17 '22 20:11

Zang MingJie