Bunder Bunder - 4 years ago 98
Java Question

Immutability of Java objects in Scala

Why this

import java.util.HashMap
val hm = new HashMap[String, String]()
hm.put("hello", "bye")
// res1: String = bye

does not pose any problem even though hm is supossed to be immutable. What am I missing?

Thanks in advance

Answer Source

It seems that you are confusing the mutability of the variable hm with the mutability of the map held by the variable, which are different. val hm means that you cannot assign hm to any other HashMap, not that the HashMap cannot be modified (as @nmat and @puhlen have explained).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download