4

How in Scala can you reference a variable to another? E.g.

import scala.collection.mutable.Set
var a = Set(1)
var b = a
a = a + 2
// a = Set(1, 2)
// b = Set(1)

I'd want b to point to the "updated" a.

Det
  • 3,640
  • 5
  • 20
  • 27

2 Answers2

3

Let's see what's going on:

scala> var a = Set(1)
a: scala.collection.mutable.Set[Int] = Set(1)

scala> var b = a
b: scala.collection.mutable.Set[Int] = Set(1)

scala> a eq b
res9: Boolean = true

That means the two variables reference the same value (in this case, mutable reference because you used var).

Now let's see what happens if we do a = a + 2:

scala> a = a + 2
a: scala.collection.mutable.Set[Int] = Set(1, 2)

scala> a eq b
res10: Boolean = false

What we should use is the += operator which, in the case of a += 2, will be desugared by the compiler as a.+=(2) (the operation += from Set) maintaining the reference of a and making the change in place. If you do a = a + 2 instead you are changing the object referenced by a to a new one a + 2 and hence changing the hashcode. And, as the data structure you are using is mutable, you can change the mutable references by immutable ones using vals.

nicodp
  • 2,362
  • 1
  • 11
  • 20
2

If you use def instead of var like this

def b = a

then accessing b will always return the latest value of a. But it is better to use val and update the Set in-place as explained in other answers to your question.

Better still, consider how you might use a more functional style and avoid having values that change over time like this.

Tim
  • 26,753
  • 2
  • 16
  • 29