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()
}
But trying to compile this sample, I get the error “test.scala:7: error: method myMethod cannot be accessed in A”.
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?
Quoting the Scala Language Specification:
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
BextendsA, an instance ofAmay access protected members of a different instance ofB… but an instance ofBmay not access protected members of anotherA! In other words: