Mutable collections
The collections of the previous lessons are immutable: a method returns a new collection and the old one stays valid, and they are the subject of lists and vectors and sets and maps. Scala also has the other kind, in scala.collection.mutable, where adding an element changes the collection the program already holds. A val says that the name cannot point at another collection; it says nothing about the contents.
A buffer and a mutable map
ArrayBuffer is the mutable list: += appends, ++= appends a whole collection, and an index can be assigned. mutable.Map has updateWith, which is the counting idiom without a lookup and an assignment:
mutable.scala
import scala.collection.mutable
@main def mutable_collections(): Unit =
val buffer = mutable.ArrayBuffer(1, 2, 3)
buffer += 4
buffer ++= List(5, 6)
buffer(0) = 10
println(buffer.toList)
buffer.remove(0)
println(buffer.toList)
println(buffer.length)
val counts = mutable.Map.empty[String, Int]
for word <- List("a", "b", "a") do
counts.updateWith(word) {
case Some(n) => Some(n + 1)
case None => Some(1)
}
println(counts.toList.sortBy(_._1))
val snapshot = buffer.toList
buffer += 7
println(snapshot)
println(buffer.toList)
scala-cli run --server=false mutable.scala
List(10, 2, 3, 4, 5, 6)
List(2, 3, 4, 5, 6)
5
List((a,2), (b,1))
List(2, 3, 4, 5, 6)
List(2, 3, 4, 5, 6, 7)
buffer += 4 changed the buffer itself, and snapshot is a copy taken before the last append: a program that hands a mutable collection to another method has given away the right to change it. The import of scala.collection.mutable at the top of the file is the signal a reader looks for, and the two names are easy to tell apart because the immutable ones need no prefix.
A mutable collection behind an immutable interface
The place a mutable collection earns its keep is a cache: the map is created inside a method, changed there, and never handed out. getOrElseUpdate computes a missing entry once and keeps it, and its second argument is by-name, so the computation runs only on a miss:
cache.scala
import scala.collection.mutable
def expensive(n: Int): Int =
println(s"computing $n")
n * n
@main def cache(): Unit =
val cache = mutable.Map.empty[Int, Int]
def square(n: Int): Int = cache.getOrElseUpdate(n, expensive(n))
println(square(4))
println(square(4))
println(square(5))
scala-cli run --server=false cache.scala
computing 4
16
16
computing 5
25
computing 4 is printed once for two calls, and computing 5 on the third, which is the whole point of the cache. The method around it is still a function of its argument: the map is a local detail, and no caller can see it.
Why the course reaches for them rarely
An immutable collection can be shared without a copy and without a lock, so it is safe to pass to another thread and safe to keep as a field. Equality is stable, because nothing changes the value after it was built; a Map used as a key does not fall out of its own hash bucket. A transformation written as map and filter says what the result is, not which order the elements were changed in, and that is the version that reads well a year later.
A mutable collection is still the right tool for a loop that would otherwise build a collection by copying, for a buffer that grows in a parser, and for a cache that lives inside one method. The rule the course follows is: keep the mutable value local, and return an immutable one — buffer.toList at the end of the method is the whole of the discipline.
Article author: Arthur Isaev