title: Scala: Getting companion objects to register themselves in repository object
body: <p>I have a bunch of singleton "worker" objects, and a central "repository" that is a thinly disguised map, mapping worker names to workers:</p>
  
  <pre><code>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)
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>object WorkerA extends Worker {
    ... 
    println("Registering A")
    Repository.register("A",this)
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>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)? </p>