Search code examples
scalaprotected

Scala qualified protected member in subclass


In Scala Language Spec. I found that

A different form of qualification is protected[this]. A member M marked with this modifier is called object-protected; it can be accessed only from within the object in which it is defined. That is, a selection p.M is only legal if the prefix is this or O.this, for some class O enclosing the reference. In addition, the restrictions for unqualified protected apply.

However I understand the case with this e.g this.protectedMember

But what I didn't get is

O.this, for some class O enclosing the reference .

please Help..

However as my understanding says that this is something that is realted with inner class as we do in Swing to get the outer class object eg OuterClass.this.someMethod in anonymous inner class.


Solution

  • The expression C.this is legal in the statement part of an enclosing class or object definition with simple name C. It stands for the object being defined by the innermost such definition.

    E.g. you can have

    class O {
      class I {
        // O.this is the instance of O this I instance is nested in
        def M = ...
        M // calls M in I
        O.this.M // calls M in O
      }
    
      protected[this] def M = ...
    }