加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 使用v.不使用`self`类型

发布时间:2020-12-16 18:41:47 所属栏目:安全 来源:网络整理
导读:鉴于以下特征: scala trait Foo { self = | def f: String = self.getClass.getName | }defined trait Fooscala trait Bar { | def f: String = this.getClass.getName | }defined trait Bar 然后创建扩展它们的类: scala class FooImpl extends Foo {} de
鉴于以下特征:

scala> trait Foo { self => 
     |   def f: String = self.getClass.getName
     | }
defined trait Foo

scala> trait Bar { 
     |  def f: String = this.getClass.getName
     | }
defined trait Bar

然后创建扩展它们的类:

scala> class FooImpl extends Foo {} 
defined class FooImpl

scala> class BarImpl extends Bar {}
defined class BarImpl

然后在新实例上调用它们的f方法:

scala> (new FooImpl).f
res1: String = FooImpl

scala> (new BarImpl).f
res4: String = BarImpl

REPL显示它们打印出相同的值 – 类的名称.

也许这不是一个好例子.但是,与使用此功能的Bar相比,使用上述Foo中的self有什么不同?

解决方法

在你的情况下没有区别 – 你只是使用另一个名称.当您需要消除不同之处的歧义时,自我类型非常有用.例如:

abstract class Foo { self =>
  def bar: Int
  def qux = new Foo {
    def bar = self.bar
  }
}

如果我们在这里写def bar = this.bar,编译器会抱怨我们对bar的定义只是递归地调用它自己,因为这将指的是我们在qux中定义的Foo的匿名子类,而不是外部Foo.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读