Protected Members of Other Instances in Scala

冷暖自知 提交于 2019-12-04 02:35:57

Quoting the Scala Language Specification:

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

– 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 is one of the reserved words this and super, or

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

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!
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!