Sunday 11 January 2015

Mutable Variable with Immutable Collections

var sisters = Vector("Melinda")
sisters = sisters :+ "Melissa"
sisters.foreach(println)

The vector itself is immutable. So the sisters variable points to a new collection each time you use the :+ method. The sisters variable is mutable—like a non-final field in Java—so it’s actually being reassigned to a new collection during each step.


A mutable variable (var) can be reassigned to point at new data.
The elements in an immutable collection (like Vector) cannot be changed.


No comments:

Post a Comment