Mutable Collections

We’ve only discussed immutable collections so far. As mentioned, we get this capability by default. To create mutable collections, we have to do an explicit import or reference to the class name.

 val​ capitals ​=
  scala.collection.mutable.Map(​"New York"​ -> ​"Albany"​, ​"Texas"​ -> ​"Austin"​)
 println(capitals)
 capitals(​"Oregon"​) ​=​ ​"Salem"
 println(​"After change: "​ + capitals)

The output from the preceding code is

 Map(Texas -> Austin, New York -> Albany)
 After change​:​ ​Map​(​Oregon​ ​->​ ​Salem​, ​Texas​ ​->​ ​Austin​, New York -> Albany)

Unlike its immutable counterpart, the mutable version of the map provides ways to insert and remove keys from the collection. Likewise, a ListBuffer allows mutation ...

Get Functional Programming: A PragPub Anthology 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.