Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala parameters for access modifiers?

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.

like image 853
pathikrit Avatar asked Jan 09 '23 12:01

pathikrit


2 Answers

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.

like image 172
Eugene Loy Avatar answered Jan 12 '23 02:01

Eugene Loy


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

like image 35
Mariusz Nosiński Avatar answered Jan 12 '23 01:01

Mariusz Nosiński