I can define a variable (by
var
) that is immutable:var x = scala.collection.immutable.Set("aaaaaa","bbbbbb") println(x.isInstanceOf[scala.collection.immutable.Set[String]]) x += "cccc" println(x.isInstanceOf[scala.collection.immutable.Set[String]])
This results in:
true true
+=
method is not a member ofscala.collection.immutable.Set
, so what is happening?
Answer
The compiler looks for x.+= ...
, and if it can’t find it, then it tries to transform the statement into x = x + ...
(which only succeeds if x
is a var
, or x
desugars into a call to some update
method). Since immutable.Set
implements a +
operator, and x
is a var
, this succeeds.
Attribution
Source : Link , Question Author : Mohammad Reza Esmaeilzadeh , Answer Author : Ken Bloom