title: Scala Immutable Set is Mutable when declaring as a var
body: <p>I'm in the process of reading Programming in Scala, 2nd Edition (fantastic book, much better than the scala's website for explaining things in a non-rockety-sciencey manner) and I noticed this...oddity when going over Immutable and Mutable Sets.</p>
  
  <p>It declares the following as an immutable set</p>
  
  <pre><code>var jetSet=Set("Boeing", "Airbus")
  jetSet+="Lear"
  println(jetSet.contains("Cessna"))
  </code></pre>
  
  <p>And then states that only Mutable sets define the += method.  Ok that makes perfect sense.  The problem is that this code works.  And the type of set created when tested in the REPL is in fact the immutable set, but it has the += method defined on it and it functions perfectly fine.  Behold</p>
  
  <pre><code>scala&gt; var a = Set("Adam", "Bill")
  a: scala.collection.immutable.Set[String] = Set(Adam, Bill)
  
  scala&gt; a += "Colleen"
  
  scala&gt; println(a)
  Set(Adam, Bill, Colleen)
  
  scala&gt; a.getClass
  res8: Class[_ &lt;: scala.collection.immutable.Set[String]] = class scala.collection.immutable.Set$Set3
  </code></pre>
  
  <p>But if I declare the Set to be a val, the Immutable Set created <strong>does not have the += method defined</strong></p>
  
  <pre><code>scala&gt; val b = Set("Adam", "Bill")
  b: scala.collection.immutable.Set[String] = Set(Adam, Bill)
  
  scala&gt; b += "Colleen"
  &lt;console&gt;:9: error: value += is not a member of scala.collection.immutable.Set[String]
            b += "Colleen"
  </code></pre>
  
  <p>What is going on here?  They both are stated to be an immutable Set but the one declared a var has access to the += method and can use it.</p>
  
  <p>Also when I kept calling the getClass method on the var Immutable Set I noticed something strange....</p>
  
  <pre><code>scala&gt; a.getClass
  res10: Class[_ &lt;: scala.collection.immutable.Set[String]] = class scala.collection.immutable.Set$Set3
  
  scala&gt; a += "One"
  
  scala&gt; a.getClass
  res12: Class[_ &lt;: scala.collection.immutable.Set[String]] = class scala.collection.immutable.Set$Set4
  
  scala&gt; a += "Two"
  
  scala&gt; a.getClass
  res14: Class[_ &lt;: scala.collection.immutable.Set[String]] = class scala.collection.immutable.HashSet$HashTrieSet
  
  scala&gt; a += "Tree"
  
  scala&gt; a.getClass
  res16: Class[_ &lt;: scala.collection.immutable.Set[String]] = class scala.collection.immutable.HashSet$HashTrieSet
  
  scala&gt; a
  res17: scala.collection.immutable.Set[String] = Set(One, Tree, Bill, Adam, Two, Colleen)
  </code></pre>
  
  <p>My guess is that thanks to some hidden syntactic sugar, Scala recognizes that it's a Var and allows you to replace it with a newly constructed set anyway.</p>