Scala parameters for access modifiers?

前端 未结 2 1848
北荒
北荒 2021-01-19 10:58

What is the difference between

class Test {
  private[this] val foo = 0
}

vs

class Test {
  private val foo = 0
}
         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 11:33

    what should I search for when I want to look up the specs of this?

    In The Scala Language Specification it is defined as "access modifier" and "access qualifier" (see BNF in §5.2).

    What is the difference between

    ...

    What all can go inside the []?

    You can put class name, package name or this there. Here is a relevant quote from language specs that explains this (see §5.2 for more details):

    The modifier can be qualified with an identifier C (e.g. private[C ]) that must denote a class or package enclosing the definition. Members labeled with such a modifier are accessible respectively only from code inside the package C or only from code inside the class C and its companion module (§5.4).

    An different form of qualification is private[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 private apply.

提交回复
热议问题