Scala parameters for access modifiers?

扶醉桌前 提交于 2019-12-20 01:10:19

问题


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).



来源:https://stackoverflow.com/questions/26664365/scala-parameters-for-access-modifiers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!