Scala parameters for access modifiers?

2019-02-23 17:29发布

问题:

What is the difference between

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

vs

class Test {
  private val foo = 0
}

What all can go inside the []? Also, what should I search for when I want to look up the specs of this? I tried Googling various combinations of "scala access modifier arguments/parametrized scala access modifier" and nothing came up.

回答1:

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.



回答2:

The first one is private for instance class, second is for class. If you use second version you have access from another instance of Test class (it's usefull for equals method or similiar).