Scala中的自我论证

  • 本文关键字:自我 Scala scala
  • 更新时间 :
  • 英文 :


此示例来自Scala书籍之一:

trait IO { self =>
  def run: Unit
  def ++(io: IO): IO = new IO {
    def run = { self.run; io.run }
  } 
}
object IO {
  def empty: IO = new IO { def run = () }
}

书中给出的解释如下:

自我论点使我们可以将此对象称为自我,而不是这个对象。

该语句意味着什么?

self只是声明对象中 this的别名,它可以是任何有效的标识符(但不是 this,否则没有别名)。因此,self可用于从内部对象内的外部对象引用this,否则this将意味着不同的东西。也许这个示例会清除问题:

trait Outer { self =>
    val a = 1
    def thisA = this.a // this refers to an instance of Outer
    def selfA = self.a // self is just an alias for this (instance of Outer)
    object Inner {
        val a = 2
        def thisA = this.a // this refers to an instance of Inner (this object)
        def selfA = self.a // self is still an alias for this (instance of Outer)
    }
}
object Outer extends Outer
Outer.a // 1
Outer.thisA // 1
Outer.selfA // 1
Outer.Inner.a // 2
Outer.Inner.thisA // 2
Outer.Inner.selfA // 1 *** From `Outer` 

最新更新