2

In a companion object, I want to have a field recording all the instances instantiated from the companion class (it is abstract), can I do that?

Especially, I thought this would reference to any instances of the subclass, but it won't compile when I use it in a companion object.

Nishant
  • 54,584
  • 13
  • 112
  • 127
user421104
  • 43
  • 3

2 Answers2

6

You'd need to code it yourself, for instance (not thread safe):

abstract class C {
  // executed by all subclasses during construction
  C.registerInstance(this) 
}


object C {
  private val instances = ListBuffer[C]()
  def registerInstance(c: C) {
    instances += c
  }
}
Iulian Dragos
  • 5,692
  • 23
  • 31
4

this in an object (doesn't matter if it's a companion object or not) refers to the object. E.g.

scala> object A { def foo = 1; def bar = this.foo } 
defined module A

scala> A.bar
res0: Int = 1
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487