In the previous chapter we learned about SCALA TYPE INFERENCE and today lets check out SCALA MUTABILITY VS IMMUTABILITY.

Mutability means you can change the value once declared. Immutability means you cannot change the value once assigned.

Mutability vs Immutability in Variables

In Scala you can declare using VAR or VAL , where VAR is mutable and VAL is immutable. Once you assign a value to VAL you cannot change it while you can change the value when you assign to VAR. Lets check it with an example. Lets assign a value to VAL and then try reassigning it

scala> val num = 5
num: Int = 5

scala> num = 6
<console>:25: error: reassignment to val
       num = 6

As you can see above I was not allowed to assign a different value and the compiler threw an error “error: reassignment to val” . Lets try doing the same with VAR

scala> var num = 5
num: Int = 5

scala> num = 6
num: Int = 6

As you can see ‘num ‘ got reassigned to 6 without any error. There is a common question which is asked as to how does the below code work if VAL is immutable.

scala> val num = 5
num: Int = 5

scala> val num = 6
num: Int = 6

The above example works because ‘num’ got a new reference variable. In simple terms, the compiler doesn’t use the same space where 5 resides rather it now points to a new space where 6 resides.


We know that Scala collections can be both Mutable and Immutable. But what happens when we mix mutable var with immutable collection ex:- Vector.

scala> var str = Vector("abc","def")
str: scala.collection.immutable.Vector[String] = Vector(abc, def)

scala> str = str :+ "ghi"
str: scala.collection.immutable.Vector[String] = Vector(abc, def, ghi)

Here something strange happens as you see that i was able to add a value to an immutable collection. But did i actually do it. What happened is, str being mutable is now pointing to a new Vector which has 3 values. We are not adding ‘ghi’ to already existing (‘abc’ , ‘def’) what we are doing is assigning (‘abc’,’def’,’ghi’) again to str.

What Immutablity in collection means is that if I would have tried to change an element in str variable it would have thrown an error. Lets change the 1st element abc and change it to xyz.

scala> str(0)="xyz"
<console>:26: error: value update is not a member of scala.collection.immutable.Vector[String]

You see that it threw an error.

You can check this beautiful example by alvinalexander on MUTABILITY VS IMMUTABILITY in Scala Collection.

In the next chapter we will learn about SCALA LAZY EVALUATION

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from UnderstandingBigData

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

Continue reading