2
在伴侶對象中,我想要一個記錄從伴侶類實例化的所有實例(它是抽象的)的字段,我可以這樣做嗎?我可以在同伴對象中使用「this」嗎?
尤其是,我認爲this
會引用該子類的任何實例,但在伴隨對象中使用它時不會編譯。
在伴侶對象中,我想要一個記錄從伴侶類實例化的所有實例(它是抽象的)的字段,我可以這樣做嗎?我可以在同伴對象中使用「this」嗎?
尤其是,我認爲this
會引用該子類的任何實例,但在伴隨對象中使用它時不會編譯。
this
在object
(無論它是否是伴侶對象)都是指對象。例如。
scala> object A { def foo = 1; def bar = this.foo }
defined module A
scala> A.bar
res0: Int = 1
你需要自己編寫它,例如(不是線程安全):
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
}
}