I am fairly new to Scala and am trying to understand the collections hierarchy. I see that there is a distinction between 'mutable' and 'immutable' collections, but I don't understand what this actually means at the implementation level and how this relates to val
and var
. Can anyone give me some insight on this? Also, does every collection class have a 'mutable' version and an 'immutable' version, or are there some classes which can only be 'mutable' or 'immutable'?
A collection in package scala. collection. immutable is guaranteed to be immutable for everyone. Such a collection will never change after it is created.
Lists are immutable whereas arrays are mutable in Scala.
Overview. Immutable objects and data structures are first-class citizens in Scala. This is because they prevent mistakes in distributed systems and provide thread-safe data. However, we can also use mutable objects if it's really necessary.
“Immutable” means that you can't change (mutate) your variables; you mark them as final in Java, or use the val keyword in Scala. More important than you not changing your variables is that other programmers can't change your variables, and you can't change theirs.
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:
val
in-place, though you can't reassign the val
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With