Scala 中其他实例的受保护成员 [英] Protected Members of Other Instances in Scala

查看:41
本文介绍了Scala 中其他实例的受保护成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习 Scala 时遇到了困难.我有一个本质上与此等效的继承层次结构:

I just ran into a difficulty while learning Scala. I have an inheritance hierarchy that is essentially equivalent to this:

class A {
    protected def myMethod() = println("myMethod() from A")
}

class B extends A {
    def invokeMyMethod(a: A) = a.myMethod()
}

但是尝试编译此示例时,出现错误test.scala:7: error: method myMethod cannot be access in A".

But trying to compile this sample, I get the error "test.scala:7: error: method myMethod cannot be accessed in A".

来自 Java,我的理解是受保护的成员应该可以从派生类的任何时候访问,而且我没有看到任何地方告诉我 Scala 中的受保护成员受实例限制.有人对此有解释吗?

Coming from Java, my understanding is that protected members should be accessible at any point from a derived class, and nowhere have I seen anything that tells me that protected members in Scala are limited by instance. Does anyone have an explanation for this?

推荐答案

引用 Scala 语言规范:

受保护的标识符 x 可以用作选择 r .x 中的成员名称仅当以下情况之一适用时:

A protected identifier x may be used as a member name in a selection r .x only if one of the following applies:

– 访问在定义成员的模板内,或者,如果给定了限定 C,则在包 C、类 C 或其伴随模块内,或

– The access is within the template defining the member, or, if a qualification C is given, inside the package C, or the class C, or its companion module, or

--r 是 this 和 super 的保留字之一,或者

– r is one of the reserved words this and super, or

– r 的类型符合包含访问权限的类的类型实例.

– r ’s type conforms to a type-instance of the class which contains the access.

这三个规则定义了何时允许一个实例访问另一个实例的受保护成员.值得注意的一件事是,根据最后一条规则,当 B 扩展 A 时,A 的实例可以访问受保护的成员B 的不同实例...但是 B 的实例不能访问另一个 A 的受保护成员!换句话说:

These three rules define when exactly an instance is allowed to access another instance's protected members. One thing that's interesting to note is that, by the last rule, when B extends A, an instance of A may access protected members of a different instance of B... but an instance of B may not access protected members of another A! In other words:

class A {
    protected val aMember = "a"
    def accessBMember(b: B) = b.bMember // legal!
}

class B extends A {
    protected val bMember = "b"
    def accessAMember(a: A) = a.aMember // illegal!
}

这篇关于Scala 中其他实例的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆