There’s a 2.8 collection walk-through by Martin Odersky which should probably be your first reference. It has been supplemented as well with architectural notes, which will be of particular interest to those who want to design their own collections.
The rest of this answer was written way before any such thing existed (in fact, before 2.8.0 itself was released).
You can find a paper about it as Scala SID #3. Other papers in that area should be interesting as well to people interested in the differences between Scala 2.7 and 2.8.
I’ll quote from the paper, selectively, and complement with some thoughts of mine. There are also some images, generated by Matthias at decodified.com, and the original SVG files can be found here.
The collection classes/traits themselves
There are actually three hierarchies of traits for the collections: one for mutable collections, one for immutable collections, and one which doesn’t make any assumptions about the collections.
There’s also a distinction between parallel, serial and maybe-parallel collections, which was introduced with Scala 2.9. I’ll talk about them in the next section. The hierarchy described in this section refers exclusively to non-parallel collections.
The following image shows the non-specific hierarchy as of Scala 2.10:
All elements shown are traits. In the other two hierarchies there are also classes directly inheriting the traits as well as classes which can be viewed as belonging in that hierarchy through implicit conversion to wrapper classes. The legend for these graphs can be found after them.
Graph for immutable hierarchy:
Graph for mutable hierarchy:
Here’s an abbreviated ASCII depiction of the collection hierarchy, for those who can’t see the images.
Traversable | | Iterable | +------------------+--------------------+ Map Set Seq | | | | | +------+-------+ SortedMap SortedSet Buffer Vector LinearSeq | | BitSet
When Scala 2.9 introduced parallel collections, one of the design goals was to make their use as seamless as possible. In the simplest terms, one can replace a non-parallel (serial) collection with a parallel one, and instantly reap the benefits.
However, since all collections until then were serial, many algorithms using them assumed and depended on the fact that they were serial. Parallel collections fed to the methods with such assumptions would fail. For this reason, all the hierarchy described in the previous section mandates serial processing.
Two new hierarchies were created to support the parallel collections.
The parallel collections hierarchy has the same names for traits, but preceded
ParSet. Note that there is
ParTraversable, since any collection supporting parallel access is capable
of supporting the stronger
ParIterable trait. It doesn’t have some of the
more specialized traits present in the serial hierarchy either. This whole
hierarchy is found under the directory
The classes implementing parallel collections also differ, with
ParHashSet for both mutable and immutable parallel collections, plus
Another hierarchy also exists that mirrors the traits of serial and parallel
collections, but with a prefix
GenSet. These traits are parents to both parallel
and serial collections. This means that a method taking a
Seq cannot receive
a parallel collection, but a method taking a
GenSeq is expected to work with
both serial and parallel collections.
Given the way these hierarchies were structured, code written for Scala 2.8 was fully compatible with Scala 2.9, and demanded serial behavior. Without being rewritten, it cannot take advantage of parallel collections, but the changes required are very small.
Using Parallel Collections
Any collection can be converted into a parallel one by calling the method
on it. Likewise, any collection can be converted into a serial one by calling
seq on it.
If the collection was already of the type requested (parallel or serial), no
conversion will take place. If one calls
seq on a parallel collection or
par on a serial collection, however, a new collection with the requested
characteristic will be generated.
Do not confuse
seq, which turns a collection into a non-parallel collection,
toSeq, which returns a
Seq created from the elements of the
toSeq on a parallel collection will return a
not a serial collection.
The Main Traits
While there are many implementing classes and subtraits, there are some basic traits in the hierarchy, each of which providing more methods or more specific guarantees, but reducing the number of classes that could implement them.
In the following subsections, I’ll give a brief description of the main traits and the idea behind them.
This trait is pretty much like trait
Traversable described below, but with
the limitation that you can only use it once. That is, any methods called on
TraversableOnce may render it unusable.
This limitation makes it possible for the same methods to be shared between the
Iterator. This makes it possible for a method that works with
Iterator but not using
Iterator-specific methods to actually be able to
work with any collection at all, plus iterators, if rewritten to accept
TraversableOnce unifies collections and iterators, and iterators are
not considered collections, it does not appear in the previous graphs, which
concern themselves only with collections.
At the top of the collection hierarchy is trait
Traversable. Its only
abstract operation is
def foreach[U](f: Elem => U)
The operation is meant to traverse all elements of the collection, and apply the given operation f to each element. The application is done for its side effect only; in fact any function result of f is discarded by foreach.
Traversable objects can be finite or infinite. An example of an infinite
traversable object is the stream of natural numbers
hasDefiniteSize indicates whether a collection is possibly infinite.
hasDefiniteSize returns true, the collection is certainly finite. If it
returns false, the collection has not been fully elaborated yet, so it might
be infinite or finite.
This class defines methods which can be efficiently implemented in terms of
foreach (over 40 of them).
This trait declares an abstract method
iterator that returns an iterator that
yields all the collection’s elements one by one. The
foreach method in
Iterable is implemented in terms of
iterator. Subclasses of
often override foreach with a direct implementation for efficiency.
Iterable also adds some less-often used methods to
can be implemented efficiently only if an
iterator is available. They are
xs.iterator An iterator that yields every element in xs, in the same order as foreach traverses elements. xs takeRight n A collection consisting of the last n elements of xs (or, some arbitrary n elements, if no order is defined). xs dropRight n The rest of the collection except xs takeRight n. xs sameElements ys A test whether xs and ys contain the same elements in the same order
Seq, Set and Map
Iterable there come three base traits which inherit from it:
Map. All three have an
apply method and all three implement the
PartialFunction trait, but the meaning of
apply is different in each case.
I trust the meaning of
Map is intuitive. After them, the
classes break up in specific implementations that offer particular guarantees
with regards to performance, and the methods it makes available as a result of
it. Also available are some traits with further refinements, such as
Base Classes and Traits
TraversableOnce– All methods and behavior common to collections and iterators.
Traversable– Basic collection class. Can be implemented just with
TraversableProxy– Proxy for a
Traversable. Just point
selfto the real collection.
TraversableView– A Traversable with some non-strict methods.
TraversableForwarder– Forwards most methods to
viewand all calls creating a new iterable object of the same kind.
immutable.Traversable– same thing as
Traversable, but restricting the collection type.
- Other special-cases
Iterableclasses, such as
Iterable– A collection for which an
Iteratorcan be created (through
Iterator– A trait which is not descendant of
count, which returns the elements seen so far.
head, which returns the next element without consuming it.
- Other special-cases
Iteratorclasses, such as
Seq– A sequence of elements. One assumes a well-defined size and element repetition. Extends
IndexedSeq– Sequences that support O(1) element access and O(1) length computation.
immutable.PagedSeq– An implementation of
IndexedSeqwhere the elements are produced on-demand by a function passed through the constructor.
immutable.Range– A delimited sequence of integers, closed on the lower end, open on the high end, and with a step.
Rangeclosed on the high end as well.
immutable.NumericRange– A more generic version of
Rangewhich works with any
immutable.RichString– Wrappers which enables seeing a
Seq[Char], while still preserving the
Stringmethods. I’m not sure what the difference between them is.
Seq-based array-like structure. Note that the “class”
Array, which is more of a memory storage method than a class.
mutable.ResizableArray– Internal class used by classes based on resizable arrays.
mutable.SynchronizedPriorityQueue– Classes implementing prioritized queues – queues where the elements are dequeued according to an
Orderingfirst, and order of queueing last.
mutable.PriorityQueueProxy– an abstract
LinearSeq– A trait for linear sequences, with efficient time for
immutable.List– An immutable, singly-linked, list implementation.
immutable.Stream– A lazy-list. Its elements are only computed on-demand, but memoized (kept in memory) afterwards. It can be theoretically infinite.
mutable.DoublyLinkedList– A list with mutable
mutable.LinkedList– A list with mutable
mutable.MutableList– A class used internally to implement classes based on mutable lists.
mutable.QueueProxy– A data structure optimized for FIFO (First-In, First-Out) operations.
immutable.Queue– A class implementing a FIFO-optimized (First-In, First-Out) data structure. There is no common superclass of both
immutable.Stack– A class implementing a LIFO-optimized (Last-In, First-Out) data structure. There is no common superclass of both
scala.xml.NodeSeq– A specialized XML class which extends
immutable.IndexedSeq– As seen above.
immutable.LinearSeq– As seen above.
mutable.ArrayStack– A class implementing a LIFO-optimized data structure using arrays. Supposedly significantly faster than a normal stack.
mutable.SynchronizedStack– Classes implementing a LIFO-optimized data structure.
mutable.Buffer– Sequence of elements which can be changed by appending, prepending or inserting new members.
mutable.ArrayBuffer– An implementation of the
mutable.Bufferclass, with constant amortized time for the append, update and random access operations. It has some specialized subclasses, such as
mutable.ListBuffer– A buffer backed by a list. It provides constant time append and prepend, with most other operations being linear.
mutable.ObservableBuffer– A mixin trait which, when mixed to a
Buffer, provides notification events through a
mutable.IndexedSeq– As seen above.
mutable.LinearSeq– As seen above.
Set– A set is a collection that includes at most one of any object.
SortedSet– A set whose elements are ordered.
immutable.BitSet– A set of integers stored as a bitset.
immutable.TreeSet– An implementation of a
SortedSetbased on a tree.
mutable.BitSet– A set of integers stored as a bitset.
immutable.HashSet– An implementation of
Setbased on element hashing.
immutable.ListSet– An implementation of
Setbased on lists.
- Additional set classes exists to provide optimized implementations for sets from 0 to 4 elements.
Proxyfor an immutable
mutable.HashSet– An implementation of
Setbased on element hashing.
mutable.ImmutableSetAdaptor– A class implementing a mutable
Setfrom an immutable
LinkedHashSet– An implementation of
Setbased on lists.
ObservableSet– A mixin trait which, when mixed with a
Set, provides notification events through a
SynchronizedSet– A mixin trait which, when mixed with a
Set, provides notification events through a
Tuple2, which also provides methods for retrieving a value (the second element of the tuple) given a key (the first element of the tuple). Extends
DefaultMap– A trait implementing some of
Map’s abstract methods.
Mapwhose keys are sorted.
immutable.TreeMap– A class implementing
immutable.HashMap– A class implementing
immutable.Mapthrough key hashing.
immutable.IntMap– A class implementing
Intkeys. Uses a tree based on the binary digits of the keys.
immutable.ListMap– A class implementing
immutable.LongMap– A class implementing
- There are additional classes optimized for an specific number of elements.
mutable.HashMap– A class implementing
mutable.Mapthrough key hashing.
mutable.ImmutableMapAdaptor– A class implementing a
mutable.Mapfrom an existing
mutable.ListMap– A class implementing
mutable.MultiMap– A class accepting more than one distinct value for each key.
mutable.ObservableMap– A mixin which, when mixed with a
Map, publishes events to observers through a
mutable.OpenHashMap– A class based on an open hashing algorithm.
mutable.SynchronizedMap– A mixin which should be mixed with a
Mapto provide a version of it with synchronized methods.
- Why the Like classes exist (e.g. TraversableLike)?
This was done to achieve maximum code reuse. The concrete generic implementation for classes with a certain structure (a traversable, a map, etc) is done in the Like classes. The classes intended for general consumption, then, override selected methods that can be optimized.
- What the companion methods are for (e.g. List.companion)?
The builder for the classes, ie, the object which knows how to create instances
of that class in a way that can be used by methods like
map, is created by a
method in the companion object. So, in order to build an object of type X, I
need to get that builder from the companion object of X. Unfortunately, there
is no way, in Scala, to get from class X to object X. Because of that, there is
a method defined in each instance of X,
companion, which returns the
companion object of class X.
While there might be some use for such method in normal programs, its target is enabling code reuse in the collection library.
- How I know what implicit objects are in scope at a given point?
You aren’t supposed to care about that. They are implicit precisely so that you don’t need to figure out how to make it work.
These implicits exists to enable the methods on the collections to be defined
on parent classes but still return a collection of the same type. For example,
map method is defined on
TraversableLike, but if you used on a
you’ll get a
This answer was originally submitted in response to this question on Stack Overflow.