Scala 中带有方括号 (private[...]) 的私有范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14706634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Private scoping with square brackets (private[...]) in Scala
提问by Scruffers
I've come across the following syntax while looking through the Gatling source code:
在查看 Gatling 源代码时,我遇到了以下语法:
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.
当我在 IDE 中单击它时,它是完全限定包 ( com.excilys.ebi.gatling.http)的别名,但我找不到该别名的定义位置。
回答by Régis Jean-Gilles
See the scala reference, specifically, chapter 5.2. Some excerpt:
请参阅scala 参考,特别是第 5.2 章。部分摘录:
The private modi?er can be used with any de?nition 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 de?nitions in parent classes.
The modi?er can be quali?ed with an identi?er C (e.g. private[C])that must denote a class or package enclosing the de?nition. Members labeled with such a modi?er 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.
私有修饰符可以与模板中的任何定义或声明一起使用。这些成员只能从直接封闭的模板及其伴随模块或伴随类(第 5.4 节)中访问。它们不被子类继承,并且它们不能覆盖父类中的定义。
修饰符可以用标识符 C(例如 private[C])来限定,该标识符必须表示包含定义的类或包。用这种修饰符标记的成员只能分别从包 C 内的代码或只能从类 C 及其配套模块内的代码访问(第 5.4 节)。此类成员也仅从 C 中的模板继承。
回答by Andy Dong
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.
- private[C] 表示访问是私有的“直到”C,其中 C 是相应的包、类或单例对象。
Same to protected[C]
与受保护的相同[C]
- protected[C]: access is protected "up to" C, where C is the corresponding package, class or singleton object.
- protected[C]:访问受保护“最多”C,其中 C 是相应的包、类或单例对象。

