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.
First of all let’s translate the
+=callThis means that we’re actually calling the
+method onSet, whose scaladoc saysWhat the code is trying to do is therefore to create a new
Setwith the added element and reassign it to the immutable referencemyset.Now if we change the reference to a mutable one (using
var) then you can reassign it with the newly made and immutableSet(1,2,3)The original Set(1, 2) is still immutable and no rule is broken. Let’s explain this with a case
As you can see, the original
Set, which is captured by theOption, was never changed, we just reassigned it’s variable reference to a newly createdSet