|
| 1 | +--- |
| 2 | +layout: overview |
| 3 | +title: Mutable and Immutable Collections |
| 4 | +disqus: true |
| 5 | +label-color: success |
| 6 | +label-text: Available in Part |
| 7 | +category: collections |
| 8 | +--- |
| 9 | + |
| 10 | +Scala collections systematically distinguish between mutable and |
| 11 | +immutable collections. A _mutable_ collection can be updated or |
| 12 | +extended in place. This means you can change, add, or remove elements |
| 13 | +of a collection as a side effect. _Immutable_ collections, by |
| 14 | +contrast, never change. You have still operations that simulate |
| 15 | +additions, removals, or updates, but those operations will in each |
| 16 | +case return a new collection and leave the old collection unchanged. |
| 17 | + |
| 18 | +All collection classes are found in the package `scala.collection` or |
| 19 | +one of its sub-packages `mutable`, `immutable`, and `generic`. Most |
| 20 | +collection classes needed by client code exist in three variants, |
| 21 | +which are located in packages `scala.collection`, |
| 22 | +`scala.collection.immutable`, and `scala.collection.mutable`, |
| 23 | +respectively. Each variant has different characteristics with respect |
| 24 | +to mutability. |
| 25 | + |
| 26 | +A collection in package `scala.collection.immutable` is guaranteed to |
| 27 | +be immutable for everyone. Such a collection will never change after |
| 28 | +it is created. Therefore, you can rely on the fact that accessing the |
| 29 | +same collection value repeatedly at different points in time will |
| 30 | +always yield a collection with the same elements. |
| 31 | + |
| 32 | +A collection in package `scala.collection.mutable` is known to have |
| 33 | +some operations that change the collection in place. So dealing with |
| 34 | +mutable collection means you need to understand which code changes |
| 35 | +which collection when. |
| 36 | + |
| 37 | +A collection in package `scala.collection` can be either mutable or |
| 38 | +immutable. For instance, [collection.IndexedSeq\[T\]](http://www.scala-lang.org/api/current/scala/collection/IndexedSeq.html) |
| 39 | +is a superclass of both [collection.immutable.IndexedSeq\[T\]](http://www.scala-lang.org/api/current/scala/collection/immutable/IndexedSeq.html) |
| 40 | +and |
| 41 | +[collection.mutable.IndexedSeq\[T\]](http://www.scala-lang.org/api/current/scala/collection/mutable/IndexedSeq.html) |
| 42 | +Generally, the root collections in |
| 43 | +package `scala.collection` define the same interface as the immutable |
| 44 | +collections, and the mutable collections in package |
| 45 | +`scala.collection.mutable` typically add some side-effecting |
| 46 | +modification operations to this immutable interface. |
| 47 | + |
| 48 | +The difference between root collections and immutable collections is |
| 49 | +that clients of an immutable collection have a guarantee that nobody |
| 50 | +can mutate the collection, whereas clients of a root collection only |
| 51 | +promise not to change the collection themselves. Even though the |
| 52 | +static type of such a collection provides no operations for modifying |
| 53 | +the collection, it might still be possible that the run-time type is a |
| 54 | +mutable collection which can be changed by other clients. |
| 55 | + |
| 56 | +By default, Scala always picks immutable collections. For instance, if |
| 57 | +you just write `Set` without any prefix or without having imported |
| 58 | +`Set` from somewhere, you get an immutable set, and if you write |
| 59 | +`Iterable` you get an immutable iterable collection, because these |
| 60 | +are the default bindings imported from the `scala` package. To get |
| 61 | +the mutable default versions, you need to write explicitly |
| 62 | +`collection.mutable.Set`, or `collection.mutable.Iterable`. |
| 63 | + |
| 64 | +A useful convention if you want to use both mutable and immutable |
| 65 | +versions of collections is to import just the package |
| 66 | +`collection.mutable`. |
| 67 | + |
| 68 | + import scala.collection.mutable |
| 69 | + |
| 70 | +Then a word like `Set` without a prefix still refers to an an immutable collection, |
| 71 | +whereas `mutable.Set` refers to the mutable counterpart. |
| 72 | + |
| 73 | +The last package in the collection hierarchy is `collection.generic`. This |
| 74 | +package contains building blocks for implementing |
| 75 | +collections. Typically, collection classes defer the implementations |
| 76 | +of some of their operations to classes in `generic`. Users of the |
| 77 | +collection framework on the other hand should need to refer to |
| 78 | +classes in `generic` only in exceptional circumstances. |
| 79 | + |
| 80 | +For convenience and backwards compatibility some important types have |
| 81 | +aliases in the `scala` package, so you can use them by their simple |
| 82 | +names without needing an import. An example is the `List` type, which |
| 83 | +can be accessed alternatively as |
| 84 | + |
| 85 | + scala.collection.immutable.List // that's where it is defined |
| 86 | + scala.List // via the alias in the scala package |
| 87 | + List // because scala._ |
| 88 | + // is always automatically imported |
| 89 | + |
| 90 | +Other types so aliased are |
| 91 | +[Traversable](http://www.scala-lang.org/api/current/scala/collection/Traversable.html), [Iterable](http://www.scala-lang.org/api/current/scala/collection/Iterable.html), [Seq](http://www.scala-lang.org/api/current/scala/collection/Seq.html), [IndexedSeq](http://www.scala-lang.org/api/current/scala/collection/IndexedSeq.html), [Iterator](http://www.scala-lang.org/api/current/scala/collection/Iterator.html), [Stream](http://www.scala-lang.org/api/current/scala/collection/immutable/Stream.html), [Vector](http://www.scala-lang.org/api/current/scala/collection/immutable/Vector.html), [StringBuilder](http://www.scala-lang.org/api/current/scala/collection/mutable/StringBuilder.html), and [Range](http://www.scala-lang.org/api/current/scala/collection/immutable/Range.html). |
| 92 | + |
| 93 | +The following figure shows all collections in package |
| 94 | +`scala.collection`. These are all high-level abstract classes or traits, which |
| 95 | +generally have mutable as well as immutable implementations. |
| 96 | + |
| 97 | +[<img src="{{ site.baseurl }}/resources/images/collections.png" width="550">]({{ site.baseurl }}/resources/images/collections.png) |
| 98 | + |
| 99 | +The following figure shows all collections in package `scala.collection.immutable`. |
| 100 | + |
| 101 | +[<img src="{{ site.baseurl }}/resources/images/collections.immutable.png" width="550">]({{ site.baseurl }}/resources/images/collections.immutable.png) |
| 102 | + |
| 103 | +And the following figure shows all collections in package `scala.collection.mutable`. |
| 104 | + |
| 105 | +[<img src="{{ site.baseurl }}/resources/images/collections.mutable.png" width="550">]({{ site.baseurl }}/resources/images/collections.mutable.png) |
| 106 | + |
| 107 | +(All three figures were generated by Matthias at decodified.com). |
| 108 | + |
| 109 | +## An Overview of the Collections API ## |
| 110 | + |
| 111 | +The most important collection classes are shown in the figures above. There is quite a bit of commonality shared by all these classes. For instance, every kind of collection can be created by the same uniform syntax, writing the collection class name followed by its elements: |
| 112 | + |
| 113 | + Traversable(1, 2, 3) |
| 114 | + Iterable("x", "y", "z") |
| 115 | + Map("x" -> 24, "y" -> 25, "z" -> 26) |
| 116 | + Set(Color.red, Color.green, Color.blue) |
| 117 | + SortedSet("hello", "world") |
| 118 | + Buffer(x, y, z) |
| 119 | + IndexedSeq(1.0, 2.0) |
| 120 | + LinearSeq(a, b, c) |
| 121 | + |
| 122 | +The same principle also applies for specific collection implementations, such as: |
| 123 | + |
| 124 | + List(1, 2, 3) |
| 125 | + HashMap("x" -> 24, "y" -> 25, "z" -> 26) |
| 126 | + |
| 127 | +All these collections get displayed with `toString` in the same way they are written above. |
| 128 | + |
| 129 | +All collections support the API provided by `Traversable`, but specialize types wherever this makes sense. For instance the `map` method in class `Traversable` returns another `Traversable` as its result. But this result type is overridden in subclasses. For instance, calling `map` on a `List` yields again a `List`, calling it on a `Set` yields again a `Set` and so on. |
| 130 | + |
| 131 | + scala> List(1, 2, 3) map (_ + 1) |
| 132 | + res0: List[Int] = List(2, 3, 4) |
| 133 | + scala> Set(1, 2, 3) map (_ * 2) |
| 134 | + res0: Set[Int] = Set(2, 4, 6) |
| 135 | + |
| 136 | +This behavior which is implemented everywhere in the collections libraries is called the _uniform return type principle_. |
| 137 | + |
| 138 | +Most of the classes in the collections hierarchy exist in three variants: root, mutable, and immutable. The only exception is the Buffer trait which only exists as a mutable collection. |
| 139 | + |
| 140 | +In the following, we will review these classes one by one. |
0 commit comments