【问题标题】:Can I use "this" in a companion object?我可以在伴生对象中使用“this”吗?
【发布时间】:2012-11-03 07:34:17
【问题描述】:

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

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

【问题讨论】:

    标签: scala companion-object


    【解决方案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
      }
    }
    

    【讨论】:

      【解决方案2】:

      object 中的this(不管它是否是伴随对象)指的是对象。例如

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

      【讨论】:

        猜你喜欢
        • 2022-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-18
        相关资源
        最近更新 更多