Scala An immutable set is Mutable when declared as var

I read the Program in Scala, 2nd Edition (a fantastic book, much better than the scala website for explaining things in a non-rocket-science style), and I noticed this ... weirdness when switching to Immutable and Mutable Sets.

He declares the following as an immutable set

var jetSet=Set("Boeing", "Airbus")
jetSet+="Lear"
println(jetSet.contains("Cessna"))

And then it states that only Mutable sets define the + = method. Well that makes sense. The problem is that this code is working. And the set type created during testing in REPL is actually immutable, but it has the + = method defined on it and it works fine. Here

scala> var a = Set("Adam", "Bill")
a: scala.collection.immutable.Set[String] = Set(Adam, Bill)

scala> a += "Colleen"

scala> println(a)
Set(Adam, Bill, Colleen)

scala> a.getClass
res8: Class[_ <: scala.collection.immutable.Set[String]] = class scala.collection.immutable.Set$Set3

But if I declare Set to be val, then in the immutable set created , the method is not set

scala> val b = Set("Adam", "Bill")
b: scala.collection.immutable.Set[String] = Set(Adam, Bill)

scala> b += "Colleen"
<console>:9: error: value += is not a member of scala.collection.immutable.Set[String]
          b += "Colleen"

? , , var, + = .

, getClass Var Immutable Set, - ....

scala> a.getClass
res10: Class[_ <: scala.collection.immutable.Set[String]] = class scala.collection.immutable.Set$Set3

scala> a += "One"

scala> a.getClass
res12: Class[_ <: scala.collection.immutable.Set[String]] = class scala.collection.immutable.Set$Set4

scala> a += "Two"

scala> a.getClass
res14: Class[_ <: scala.collection.immutable.Set[String]] = class scala.collection.immutable.HashSet$HashTrieSet

scala> a += "Tree"

scala> a.getClass
res16: Class[_ <: scala.collection.immutable.Set[String]] = class scala.collection.immutable.HashSet$HashTrieSet

scala> a
res17: scala.collection.immutable.Set[String] = Set(One, Tree, Bill, Adam, Two, Colleen)

, scala , Var .

+4
1

, mutable Set, .

a += "Colleen"

, a

Scala ,

a = a + "Colleen"

, += ( Set)

, += , a val, , .

Scala ( 17.3)

, , Scala . , +=, Scala +=. , a += b a +=, Scala a = a + b

, .

+12

All Articles