Pooya
Pooya

Reputation: 4481

How to share an item between derived classes of a trait in Scala?

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

Answers (1)

0__
0__

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

Related Questions