Consider the following:
scala> val myset = Set(1,2)
myset: scala.collection.immutable.Set[Int] = Set(1, 2)
scala> myset += 3
<console>:9: error: reassignment to val
myset += 3
^
scala> var myset = Set(1,2)
myset: scala.collection.immutable.Set[Int] = Set(1, 2)
scala> myset += 3
scala> myset
res47: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
In one case I can add "alex" and in another I can't. I know the difference between val and var. However what confused me in both cases Scala tells me that the Set is immutable but it allows different behaviour.
I don't want to just as that's because in oncase myset is a val and in one it is a var. I want a deeper answer than that to explain why in both cases Scala says myset is an immutable set but yet treats both differently. Because it is counter intuitive.
For example, is there any difference using a mutuable set and declaring an immutable set as var? And why does scala let you bend the rules? Would it not be better if when it is said immutable it meant it?
Thanks.