Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutable vs. immutable in Scala collections

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'?

like image 487
astay13 Avatar asked Nov 27 '11 17:11

astay13


People also ask

Does Scala have immutable collections?

A collection in package scala. collection. immutable is guaranteed to be immutable for everyone. Such a collection will never change after it is created.

Is list mutable or immutable in Scala?

Lists are immutable whereas arrays are mutable in Scala.

Are objects immutable 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.

What is immutable data in Scala?

“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.


1 Answers

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:

  1. You can modify a mutable collection bound to a val in-place, though you can't reassign the val
  2. 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.

like image 156
Fred Foo Avatar answered Sep 17 '22 18:09

Fred Foo