Search code examples
scalascala-2.12

Why a Map is by default immutable in Scala?


With scala (2.12.2), when creating a new Map in a class

private var myMap = Map.empty[String, ActorRef]

by default I get a immutable class

scala.collection.immutable.Map[String,akka.actor.ActorRef]

I was expecting to be mutable because I define it as 'var'


Solution

  • What's mutable here is the reference held by myMap, you can re-assign the variable if you want to. Mutability or immutability of the value pointed to be that reference is a different matter. If you create a mutable map, you can assign it to a variable declared via val and can modify the map, but not the variable.