I am from Java background and trying to learn Scala.
There is an example as below in the book "Programming in Scala - Third Edition"
var jetSet = Set("Boeing", "Airbus")
jetSet += "Lear"
println(jetSet.contains("Cessna"))
The first line creates an immutable non-final Set:
jetSet: scala.collection.immutable.Set[String] = Set(Boeing, Airbus)
The second line runs with no errors.
Now, when I change the first line from var to val, the second line gives error:
<console>:13: error: value += is not a member of scala.collection.immutable.Set[String]
jetSet += "Lear"
I am not able to understand the reason behind it. val corresponds to final and var is non-final. I am not assigning the variable to any new Set. In both the cases, the Set is immutable.
How is var or val impacting things here?
Also, when jetSet is immutable in both the cases, why is it allowing to add a new value to the set in the case of var. Does it not violate the immutability principle.
Correct my understanding, please.