O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required