Mutable means you can alter the collection in-place. So, if you have a collection c
and you append an element with +=
, then c
has changed, and so has every other reference to that collection.
Immutable means that the collection object never changes; instead, you build new collection objects with operations such as +
or ++
, which return a new collection. This is useful in concurrent algorithms, since it requires no locking to add something to a collection. It may come at the cost of some overhead, but this property can be very useful. Scala's immutable collections are fully persistent data structures.
The difference is very similar to that between var
and val
, but mind you:
- You can modify a mutable collection bound to a
val
in-place, though you can't reassign the val
- you can't modify an immutable collection in-place, but if it's assigned to a
var
, you can reassign that var
to a collection built from it by an operation such as +
.
Not all collections necessarily exist in mutable and immutable variants; the last time I checked, only mutable priority queues were supported.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…