Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semantics of Scala Traversable, Iterable, Sequence, Stream and View?

There are other questions such as Scala: What is the difference between Traversable and Iterable traits in Scala collections? and How would I get the sum of squares of two Lists in Scala? that answers the question partially. I felt a question that covers all of this in one place makes sense.

like image 661
smartnut007 Avatar asked Dec 20 '11 00:12

smartnut007


1 Answers

Traversable is the top of the collections hierarchy. Its main method is 'foreach' so it allows to do something for each element of the collection.

An Iterable can create an Iterator, based on which foreach can be implemented. This defines some order of the elements, although that order might change for every Iterator.

Seq(uence) is an Iterable where the order of elements is fixed. Therefore it makes sense to talk about the index of an element.

Streams are lazy Sequences. I.e. elements of a stream may not be computed before they are accessed. This makes it possible to work with infinite sequences like the sequence of all integers.

Views are non-strict versions of collections. Methods like filter and map on view only execute the passed functions when the respective element gets accessed. Thus a map on a huge collection returns immediately because it just creates a wrapper around the original collection. Only when one accesses an element, the mapping gets actually executed (for that element). Note that View is not a class, but there are lots of XxxView classes for various collections.

like image 64
Jens Schauder Avatar answered Oct 03 '22 08:10

Jens Schauder