Collections · 27 of 42

Mutable Collections

Scala “encourages” using immutable collections (hence they are the ones used by default), however sometimes mutable collections might have some benefits, either for CPU / memory performance, for code readability or simply a matter of preference. As we saw earlier, Scala provides concrete mutable collections in scala.collection.mutable.

  • Best practice suggests that you prefix mutable collections with mutable; this might not seem useful for ArrayBuffer, but it will for scala.collection.mutable.Map
  • ArrayBuffer is more or less the equivalent of Java’s java.util.ArrayList, which is backed by an array
  • ListBuffer is the mutable partner for Scala’s immutable List, implemented as a linked list
  • There are many other mutable collection types, see the links below for more information
import scala.collection.mutable

mutable.ArrayBuffer(1, 2, 3)
mutable.ListBuffer("a", "b", "c")
mutable.Set(0.1, 0.2, 0.3)
mutable.Map("one" -> 1, "two" -> 2)

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties