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")**
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
.