How do you declare an immutable collection in Scala?

Instruction: Describe the process of creating an immutable collection in Scala and explain its advantages.

Context: This question assesses the candidate's knowledge of Scala's collection types, focusing on immutable collections, their declaration, and their benefits over mutable collections.

Updated

Use an immutable collection type such as List, Vector, or an explicitly qualified immutable Map:

@main def immutableExample(): Unit = {
  val numbers: List[Int] = List(1, 2, 3)
  val extended: List[Int] = 0 :: numbers
  val lookup = scala.collection.immutable.Map("a" -> 1)
  val updated = lookup.updated("a", 2)
  assert(numbers == List(1, 2, 3))
  assert(extended == List(0, 1, 2, 3))
  assert(lookup("a") == 1 && updated("a") == 2)
}

The update returns a new collection value, leaving the earlier one intact. Implementations can share unchanged structure instead of copying every element. This makes it easier to pass snapshots between functions and reason about which value a computation uses. Mutable and immutable collections

Distinguish the binding from the object: a val binding to a mutable ArrayBuffer prevents rebinding the variable, but the buffer can still be mutated. Conversely, a var can be reassigned to a different immutable collection.

Collection immutability is not recursive. A List of mutable objects still contains references to mutable objects, and sharing those elements between threads can require synchronization. Immutable structure alone also does not make a compound update of a shared reference atomic.

Select a collection by its operations: lists support efficient prepend/head/tail access, while indexed sequences suit indexed access. Immutable updates have allocation and traversal costs that depend on the structure; they are not universally faster than controlled local mutation.

Related Questions