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

Scala:访问伴随对象特征的受保护字段

发布时间:2020-12-16 18:42:40 所属栏目:安全 来源:网络整理
导读:我有一个Trait,一个Companion对象和一个 Scala中的类: trait A { protected var foo = "Foo"}object B extends A {}class B { println(B.foo)} 为什么我不能访问foo?我以为foo会成为对象“B”的一个字段.有没有办法做到这一点? 解决方法 规范说您可以访问
我有一个Trait,一个Companion对象和一个 Scala中的类:

trait A {
    protected var foo = "Foo"
}

object B extends A {
}

class B {
     println(B.foo)
}

为什么我不能访问foo?我以为foo会成为对象“B”的一个字段.有没有办法做到这一点?

解决方法

规范说您可以访问受保护的成员:

the companion module of any of those classes [that have the defining template as a base].

也就是说,不是来自以定义模板为基础的对象的伴随类.棘手.

由于“模块”命名法,这一点并不明显,模块只是意味着对象.偶尔谈论改变这种情况.虽然类和模块可以是伴侣,但关系不是对称的;考虑隐式搜索.

trait A {
  protected var foo = "Foo"
  protected def bar = "Bar"
}

object B extends A {
  //override protected var foo = super.foo // no
  override protected def bar = super.bar
}

class B {
  //println(B.foo) // no
  println(B.bar) // ok
}


class C extends A

object C {
  println(new C().foo)  // ok
}

(编辑:李大同)

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

    推荐文章
      热点阅读