Collections And (Im)Mutability in Scala (Part-1)

Reading Time: 5 minutes

Collections in Scala systematically distinguish between mutable and immutable collection. In this blog we are gonna discuss Mutability of Immutable collections in Scala.

Collections in Scala –

These are nothing, just like containers. Those containers can be Sequence, Set or Map. Scala provides a rich set of Collections library which can be mutable or immutable.

In Scala, Collections are classified into 3 categories with the following hierarchy.

The above figure intimate all the collections in “scala.collection”. These all are either high level abstract class or traits. They are in general have mutable and immutable implementation which we’ll discuss later in this blog.

Just for curiosity, all these classes shares quite a bit of commonality. For illustration, every type of collection can be declared by the same uniform syntax i.e. writing the collection class name followed by its elements.

Let’s discuss Set, Seq and Map, and bit of their types too.

1. Set –

Scala set is used to store unique elements in the Set. It bedrock on the uniqueness of elements being stored in it rather than maintaining the order of elements in which the elements are stored.

Let’s discuss some of it’s types i.e. HashSet, BitSet and ListSet.

1.1 HashSet –

Scala HashSet is a sealed class which extends Abstract Set and immutable Set Traits. Such type of collection uses hash codes to store elements.

1.2 BitSet-

Scala BitSet is sets of non-negative integers extending the set trait which are represented as variable-size arrays of bits packed into 64-bit words. The memory footprint of a bitset is determined by the largest number stored in it.

1.3 ListSet-

Scala ListSet extends immutable sets using a list-based data structure. In it, the elements are stored in reversed order, that means the newest will be at top/head of list maintaining the insertion order.

2. Seq –

Scala Seq is a trait which represents indexed sequences, guaranteeing the immutability .Thus, you can access the elements by using their indexes. Also, It maintains insertion order of elements. Additionally, it support a number of methods to find occurrences of elements or it’s sub-sequences.

Let’s discuss some of it’s types i.e. Vector, List, Queue and Stream.

2.1 Vector-

Scala Vector is an immutable and general-purpose data structure extending the abstract class AbstractSeq and IndexedSeq trait.. And when it comes to large collection of elements, Vector is pretty good to use.

2.2 List-

Scala List is collection used to store the elements, maintaining the order in which they stored in the list extending the LinearSeq trait. It is good for stack-like access patterns means last-in-first-out (LIFO).

2.3 Queue-

Scala Queue, a data structure implementing a pair of lists.One is used to insert and second is used to contain the deleted elements. In other words, elements are stored in first list and removed from the second list. This type of collection allows you to retrieve and insert the elements in FIFO manner.

2.4 Stream-

Scala Stream is a feature of Scala which uses lazy lists. It supports lazy evaluation i.e. evaluates only when required.

As the above example illustrates that it only access the elements when required thus improves the performance of program.

3. Map

Scala Map, like other collections is also used to store elements. It stores the elements as a pair of key and value. In Scala, you can create the map in two ways either by using the comma separated pairs or by using rocket operator. Consider the following example to understand this.

Let’s discuss some of it’s types i.e. HashMap and ListMap.

3.1 HashMap-

Scala HashMap is a map which uses hash code to store elements and returns a map.

3.2 ListMap-

Scala ListMap, a collection (Map) implementing maps using a list-based data structure returning a ListMap. This type of collection is pretty good to use for small elements.


In Scala, it come in three flavors as follows –

Scala Packages

Mutability in Scala –

In simple words mutability means that you can modify your collections later on. They can be updated or extended in place hence we can change, add, or remove elements of a collection as a side effect.

A collection in package “collection.mutable” is known to have some operations.You can change it in place. Mutability in Scala means you need to understand which code changes which collection and when.

Immutability in Scala –

By Contrast collection that can’t change are Immutable collections. In such case you still can do operations that simulate addition, removals or updates. But those operations will return a new collection, leaving the old collection unchanged.

A collection in package “collection.immutable” is guaranteed to be immutable for everyone. Such a collection will never change.

Note : By default (without imports) the immutable collections are used with one Exception. ‘Seq’ refers to “scala.collection.Seq” because of Arrays. So, It’s a good practice to use Immutable collection in Scala.

Mutating Immutable Collection

Let’s try to understand this by creating a list in Scala as follows

Creating list in Scala

We have discussed that collections are immutable thus the List ‘myList’ will be immutable. Now, Let’s try to add an element into it.

Collections in Scala

It seems like the element has been added to the list but actually isn’t. Let’s verify it by accessing the elements of the List ‘myList’.

Collections in Scala

Conclusion

  • Immutable collection can not be mutated in place.
  • Mutating operations always return a new instance.
  • Mutable collections are persistent (share data structurally).

In fact for Best Practice, start immutable and know the performance characteristics.

References

Stay Tuned …

In this blog, we have gone through the overview of Collections in Scala. Stay tuned for next part of Collections in Scala, where we’ll discuss them in details. You don’t wanna miss it….

Written by 

Kuldeepak Gupta is a passionate software consultant at Knoldus Inc. Knoldus does niche Reactive and Big Data product development on Scala, Spark, and Functional Java. His current passions include utilizing the power of Scala, Akka, and Play to make Reactive and Big Data systems. He is a self-motivated, enthusiastic person who is recognized as a good team player, dedicated, responsible professional, and a technology enthusiast. His hobbies include playing hockey, participating in Political debates, Reading Tech blogs, and listening to songs.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading