Immutable Var vs Mutable Val

In general, Immutable objects are considered better than mutable objects, most of the times (read almost all the time).  This stack overflow link explains it pretty well in case you want to know more.

Today’s blog post is about a very similar topic and pertains to situation where you want a data structure where you can to add more data over the course of execution of the program. Now how can you do it ? Well, there are two standard and straightforward ways by which you can do this :

  1. Create a immutable reference but mutable data structure.
    val mutableMap = new MutableMap()
    and if you are gonna add a object, you would do,
    mutableMap.add(Key, Value)
  2. Other option is to create mutable reference but immutable data structure.
    var immutableMap = new ImmutableMap()
    If you want to add an object here, this is how you will do it :
    immutableMap = immutableMap ++ Map(Key -> Value)
    It will always change the reference, but at any point, the object pointed by the reference will not change the object contents.

Can you tell me which approach is better ?

Option 2.

Why, you ask ?
Well, for one thing, if you are passing the above map as an argument to a method, would you want the map to change in between while it is being processed by the method? You can probably manage it by incorporating some more required changes in your code but those kind of changes are very hard to reason about.
It is also bad for readability and cohesion if you are going through the code and makes for some nasty bug and also reduces unit testability.  Even if you know what you are doing and if it is possible to go with option 2 with the way you are designing you class, you should always go with Option 2.
Just my two cents.

Immutable Var vs Mutable Val