Abhinav Kumar
Abhinav Kumar

Reputation: 240

How can a Map or List be immutable when we can add or remove elements from them?

Below is a scala code to declare a immutable Map

var m:Map[Int,String] = Map(1->"hi",2->"hello")
println(m)
// Result: Map(1->"hi",2->"hello")

Here we are able to add or change the content of Map, then how can we say a map or list in scala are immutable

m=m+(3->"hey") 
println(m)
// Result: Map(1->"hi",2->"hello",3->"hey")**

Upvotes: 1

Views: 484

Answers (2)

Vladimir Matveev
Vladimir Matveev

Reputation: 127781

Even if you think that your question is not about var or val, it actually is: in your example it is very important whether m is defined as var or val. In your example, even though you see that the map has changed, it actually has not: your code creates another map and assigns it to the same variable. The map itself has not changed, because it is immutable. You can observe this in this code:

val m1 = Map(1 -> "hi", 2 -> "hello")

var m = m1
m = m + (3 -> "hey")

println(m)   // prints Map(1 -> ..., 2 -> ..., 3 -> ...)
println(m1)  // prints Map(1 -> ..., 2 -> ...)

If Map was mutable here, you would have seen that m1 has also changed. Because you don't see this, it means that the map is not mutable, only the variable is.

Upvotes: 4

Gal Naor
Gal Naor

Reputation: 2397

Map is immutable, but you used a mutable variable m (because you declare it as var).

This line m=m+(3->"hey") actually creates a new map and assigned it to your variable m.

Try to declare m as val and see that you will get a compilation error.

But - if you will use mutable map:

val m = scala.collection.mutable.Map[Int,String]

You will be able to update this map (while you can't do this with immutable map) -

m(3) = "hey"

or

m.put(3,"hey")

This is how you will update the content of the map, without recreating it or changing the variable m (like you did before with m = m + ...), because here m is declared as val, which makes it immutable, but the map is mutable.

You still can't do m = m + .. when it's declared as val.

Please refer to this answer about the differences between var and val.

Upvotes: 8

Related Questions