Problem Statement
Explain the difference between mutable and immutable collections and when to use each.
Explanation
Immutable collections created with listOf, setOf, or mapOf don't have methods to add or remove elements, providing a read-only view that prevents modifications through that reference. Mutable collections created with mutableListOf, mutableSetOf, or mutableMapOf provide methods like add, remove, and clear for modifications.
Prefer immutable collections as the default choice because they're safer in concurrent code, prevent accidental modifications, make code easier to reason about, and clearly communicate that the collection won't change. Use mutable collections when you need to build collections incrementally or when performance requires in-place modifications.
Note that immutable doesn't mean the underlying implementation is unchangeable, just that the interface prevents modifications. For true immutability use defensive copying or immutable data structures libraries.
Good practice is to use mutable collections internally during construction, then expose them as immutable interfaces to callers using toList or returning List type instead of MutableList, protecting your internal state while allowing internal modifications.
Practice Sets
This question appears in the following practice sets: