2012-11-03 29 views
2

在伴侶對象中,我想要一個記錄從伴侶類實例化的所有實例(它是抽象的)的字段,我可以這樣做嗎?我可以在同伴對象中使用「this」嗎?

尤其是,我認爲this會引用該子類的任何實例,但在伴隨對象中使用它時不會編譯。

回答

4

thisobject(無論它是否是伴侶對象)都是指對象。例如。

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

scala> A.bar 
res0: Int = 1 
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 
    } 
} 
相關問題