10.1. Understanding the Collections Hierarchy

Problem

The Scala collections hierarchy is very rich (deep and wide), and understanding how it’s organized can be helpful when choosing a collection to solve a problem.

Solution

Figure 10-1, which shows the traits from which the Vector class inherits, demonstrates some of the complexity of the Scala collections hierarchy.

The traits inherited by the Vector class

Figure 10-1. The traits inherited by the Vector class

Because Scala classes can inherit from traits, and well-designed traits are granular, a class hierarchy can look like this. However, don’t let Figure 10-1 throw you for a loop: you don’t need to know all those traits to use a Vector. In fact, using a Vector is straightforward:

val v = Vector(1, 2, 3)
v.sum                   // 6
v.filter(_ > 1)         // Vector(2, 3)
v.map(_ * 2)            // Vector(2, 4, 6)

At a high level, Scala’s collection classes begin with the Traversable and Iterable traits, and extend into the three main categories of sequences (Seq), sets (Set), and maps (Map). Sequences further branch off into indexed and linear sequences, as shown in Figure 10-2.

A high-level view of the Scala collections

Figure 10-2. A high-level view of the Scala collections

The Traversable trait lets you traverse an entire collection, and its Scaladoc states that it “implements the behavior common to all collections in terms of a foreach method,” which lets ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.