Private scoping with square brackets (private[…])

2019-02-02 21:14发布

问题:

I've come across the following syntax while looking through the Gatling source code:

private[http] def build = {
  // ...
}

What is the syntax inside square brackets?

When I click through it in my IDE it is an alias to a fully qualified package (com.excilys.ebi.gatling.http) but I can't find where that alias was defined.

回答1:

See the scala reference, specifically, chapter 5.2. Some excerpt:

The private modifier can be used with any definition or declaration in a template. Such members can be accessed only from within the directly enclosing template and its companion module or companion class (§5.4). They are not inherited by subclasses and they may not override definitions in parent classes.

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). Such members are also inherited only from templates inside C.



回答2:

In short: this is used for scope protection:

  • private[C] means that access is private "up to" C, where C is the corresponding package, class or singleton object.

Same to protected[C]

  • protected[C]: access is protected "up to" C, where C is the corresponding package, class or singleton object.