Home > Back-end >  assignment of two Scala class instances
assignment of two Scala class instances

Time:01-24

class Counter {
  var counter: Int = 0
  def increaseCounter(): Unit =
    counter = counter   1
}

var counter1 = new Counter
var counter2 = new Counter

counter1 = counter2

counter1.increaseCounter()
counter2.counter // => 1

I do not really understand why the counter of counter2 is changed even though I only changed the counter of counter1. Are Scala class instances just pointers and in this case counter1 and counter2 are pointing to the same object?

CodePudding user response:

Scala variables are just pointers, so this:

counter1 = counter2

makes both counter1 and counter2 point to the same instance.

This kind of hidden dependency is why you should avoid var as much as possible and always create new objects rather than modifying existing objects.

CodePudding user response:

Yes. Just like in Java. This you did is a shallow copy. If you want to assign the value of one be copied to the other you need a deep copy. You need counter1.counter = counter2.counter

  •  Tags:  
  • Related