I have a bunch of singleton "worker" objects, and a central "repository" that is a thinly disguised map, mapping worker names to workers:
trait Worker { def work(): String }
object WorkerA extends Worker { [...] }
[...]
object WorkerX extends Worker { [...] }
object Repository {
private val repo: scala.collection.mutable.Map[String,Worker] = Map()
def register(name:String,worker:Worker) = repo.put(name,worker)
}
I would really like the Repository to be automatically populated with all the workers at start of the program, so I tried something like this:
object WorkerA extends Worker {
...
println("Registering A")
Repository.register("A",this)
}
but to my surprise "Registering A" was never printed (and the worker was not registered at the repository). I found out that this is because Scala is lazy about initializing companion objects.
So, is there a way to force non-lazy initialization, or any other way that I can do what I want in Scala (short of using reflection or keeping an explicit list of workers in the definition of Repository)?