Reputation: 51
In scala, you can have 2 types of set where the elements are immutable or mutable, But as you cannot index these sets, so how can you change the elements of the latter sets??
Upvotes: 0
Views: 1111
Reputation: 369604
In scala, you can have 2 types of set where the elements are immutable or mutable
That is not what the distinction between scala.collection.immutable.Set
and scala.collection.mutable.Set
is. It is not about mutability or immutability of the elements, it is about mutability or immutability of the sets themselves.
But as you cannot index these sets, so how can you change the elements of the latter sets
It is not about changing the elements of mutable sets. It is about changing the mutable sets themselves:
import scala.collection.mutable.{ Set => MSet}
import scala.collection.immutable.{Set => ISet}
val mset = MSet(1, 2, 3)
val iset = ISet(1, 2, 3)
mset += 4
mset //=> HashSet(1, 2, 3, 4): scala.collection.mutable.Set[Int]
val iset2 = iset + 4
iset //=> Set(1, 2, 3): scala.collection.immutable.Set[Int]
iset2 //=> Set(1, 2, 3, 4): scala.collection.immutable.Set[Int]
iset += 4
// ERROR: value += is not a member of scala.collection.immutable.Set[Int]
The difference between the two is that you can't add an element to an immutable set. Instead, when you call the scala.collection.immutable.Set.+(elem: A): Set[A]
method, it will return a new set (iset2
in this case) that has the same elements as the original set (iset
) plus the element we wanted to add.
Whereas the scala.collection.mutable.Set.+=(elem: A): Set.this.type
method returns the same set (and in fact, as you can see in my example above, I actually ignore the return value) and mutates it to contain the additional element.
In Scala, the idea of a set is much closer to the mathematical idea of sets instead of as a collection. It is not a collection that contains the elements, rather it is a predicate function that you can ask "is this element a member of the set"?
Upvotes: 3