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参数允许我们将此对象称为self而不是this.

那句话意味着什么?

解决方法

self只是声明它的对象中的别名,它可以是任何有效的标识符(但不是这个,否则不会产生别名).因此,self可以用来从内部对象中的外部对象引用它,否则这将意味着不同的东西.也许这个例子可以解决问题:

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`

猜你在找的Scala相关文章