Scala: Understanding mutable variables with immutable collections
By Alvin Alexander. Last updated: January 24 2018
This is an excerpt from the Scala Cookbook (partially re-worded for the internet). This is Recipe 10.6, “Understanding Mutable Variables with Immutable Collections.”
Problem
You may have seen that mixing a mutable variable (var
) with an immutable collection causes surprising behavior. For instance, when you create an immutable Vector
as a var
, it appears you can somehow add new elements to it: