Frank Kong
Frank Kong

Reputation: 1072

Confusion about mutable and immutable set in scala

Hello I am new to scala and I am confused about method set.+(element). when I do this

var set_1: scala.collection.immutable.Set[Int] = scala.collection.immutable.Set[Int](2)
set_1.+=(1)
println(set_1)

val set_1: scala.collection.mutable.Set[Int] = scala.collection.mutable.Set[Int](2)
set_1.+=(1)
println(set_1)

I get result as Set(1, 2) for both of them. First one I used "var" and "immutable", second one I used "val" and "mutable". What is mechanism of .+() method? It reassign the variable set_1 or modify the value of set_1? can anyone help me?

Upvotes: 2

Views: 171

Answers (2)

justinhj
justinhj

Reputation: 11306

In the first case you're using an immutable set but you're storing it in a var. When you call "+=" the result is analogous to the following except instead of creating a new variable set2 you are storing the new set in the variable set1...

val set1 = Set(2)
val set2 = set1 + Set(1)

The original Set(2) is never modified, instead a new set is created. That new set is then assigned as the value of the mutable variable set1.

In the second case the variable set1 points to a mutable set. You create the set Set(1), then modify that same set to contain Set(1,2)

There are use cases for both, but personally I would use the immutable set most of the time as it is easier to reason about.

Upvotes: 3

Dima
Dima

Reputation: 40500

In my opinion, the first example should not compile. =+ in this case is an operator, applied to the var set_1, but set_1.+= syntax makes it look like a regular method call on the instance set_1 is referring to. This is what causes the confusion.

Upvotes: -3

Related Questions