Reputation: 4481
I have a trait and a lot of class that implemented it, each class has some methods that should increase a global or shared synchronized value between all of the other derived classes, as you know, in Scala you can't declare a static variable or method class or trait. What is the best design to solve this problem in Scala? Should I pass an object between all of the derived classes? I think this approach, will decrease the extensibility of the code
Upvotes: 1
Views: 423
Reputation: 67310
Leaving aside considerations whether maintaining global state is a good idea; you can use a singleton object:
object Foo {
var state = 0
}
trait Foo
class Bar extends Foo {
Foo.state += 1
}
class Baz extends Foo {
Foo.state -= 1
}
Upvotes: 2