gpt4 book ai didi

scala - Scala 中的自论证

转载 作者:行者123 更新时间:2023-12-02 17:44:29 25 4
gpt4 key购买 nike

这个例子来自一本 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 只是声明它的对象中 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`

关于scala - Scala 中的自论证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30108539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com