Scala中的自我论证
发布时间:2020-12-16 18:05:35 所属栏目:安全 来源:网络整理
导读:这个例子来自 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而不是th
这个例子来自
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` (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |