Abstracting on Sequences
All Scala
collections descend from a common trait called
Traversable
. The design adopted for Scala collections allows one
to use higher-order functions similarly in nearly all collections, with proper return types in specific instances. Treating collections as sequences, or as containers of elements, allows one to use different data structures seamlessly.
The Traversable Trait
At the root
of the collections hierarchy is the
Traversable
trait. The
Traversable
trait has a single abstract method:
def foreach[U](f: Elem => U)
The implementation of this method is sufficient for the
Traversable
trait to provide a series of useful higher-order methods.
We would like to focus on the
map
operations. The
map
method takes a function and applies it to every element of the collection.
Let's experiment with the
map
method in the Scala
REPL
and show how it applies to different types of collections. For now, create a function that multiplies an integer by 2 and apply...