我可以在伴侣对象中使用“this”吗?

时间:2012-11-03 07:34:17

标签: scala companion-object

在一个伴侣对象中,我希望有一个字段记录从伴侣类中实例化的所有实例(它是抽象的),我可以这样做吗?

特别是,我认为this会引用子类的任何实例,但是当我在伴随对象中使用它时它将无法编译。

2 个答案:

答案 0 :(得分:6)

例如,您需要自己编码(非线程安全):

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
  }
}

答案 1 :(得分:4)

this中的{p> object(如果它是伴侣对象,则无关紧要)是指对象。 E.g。

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

scala> A.bar
res0: Int = 1
相关问题