0

I have a trait that is extended by two classes. Is there any way that change made to a trait variable from one class reflect in the second class?

Let's see for a simple code like this

trait parent {
    var a: Int = 0;
}

class child1 extends parent {
    def setValue(n: Int) = a = n
}

class child2 extends parent {
    def getValue() : Int = a
}

object parentTest extends App {
    val c = new child1()
    c.setValue(2)
    val d = new child2()
    println(d.getValue)
}

I want to have d value printed as 2. If not with traits, is there any other way to access the same variable across multiple classes so that changes made in one also appear to other class?

vinayawsm
  • 845
  • 9
  • 28
  • What exactly are you doing? Rewriting your own Future-Promise implementation? If not - what are you trying to do, exactly? Communicate over shared mutable state? – Andrey Tyukin Oct 25 '18 at 20:08
  • @AndreyTyukin Working on a distributed program. I update these values in worker nodes and want to read them in the master node. I can send the values from worker to master but these are just indexing/storage variables and not result of any operations so do not want to pass them from worker to master. – vinayawsm Oct 25 '18 at 20:50
  • 1
    So, you *are* using shared mutable state for communication in a distributed program. That never ends well, please don't do this. Use something like Akka instead. – Andrey Tyukin Oct 25 '18 at 20:51
  • Sure, will check that. Thank you. – vinayawsm Oct 25 '18 at 20:53

2 Answers2

1

Put the var in a companion object and put the setter and getter code in the trait.

object Parent {private var a :Int = 0}
trait Parent {
  def set(x :Int) :Unit = Parent.a = x
  def get :Int = Parent.a
}

class Child1 extends Parent
class Child2 extends Parent

val c1 = new Child1
val c2 = new Child2
c1.set(9)  //res0: Unit = ()
c2.get     //res1: Int = 9

Parent.a = 6 //Error: variable a in object Parent cannot be accessed in object A$A83.this.Parent

If the var is private then it can only be accessed in the companion trait.

jwvh
  • 50,871
  • 7
  • 38
  • 64
0

In Java you would use static variables, Scala solves most of these use-cases using companion objects.

You could create your trait so it stores the variable using a (companion) object.

A drawback would be that anyone with access to the object could modify its state, but I think a java + static solution probably would have the same drawback. If you want to prevent this I think you'd need some sort of a factory to create the instances of your classes that will provide them a shared variable reference during construction.

Simon Groenewolt
  • 10,607
  • 1
  • 36
  • 64