Reputation: 865
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?
Upvotes: 0
Views: 479
Reputation: 51271
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.
Upvotes: 1
Reputation: 10665
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.
Upvotes: 0