Scala Working with data in immutable style
It is not just val vs. var
val and var
• val references are unchangeable: like a final variable in Java, once it has been initialized you cannot change it
• var references are reassignable as a simple variable declaration in Java
Immutable and Mutable collections
The Scala standard library offers both immutable and mutable data structures, not the reference to it. Each time an immutable data structure get "modified", a new instance is produced instead of modifying the original collection in-place. Each instance of the collection may share significant structure with another instance.
But I can't use immutability in this case!
Let's pick as an example a function that takes 2 Map and return a Map containing every element in ma and mb:
A first attempt could be iterating through the elements of one of the maps using for ((k, v) <- map) and somehow return the merged map.
This very first move immediately add a constrain: a mutation outside that for is now needed. This is more clear when de-sugaring the for: