2

I am new to scala, could anyone pinpoints what kind of terminology for the below square bracket [this] ?

private[this] lazy val outputAttributes = AttributeSeq(output)

Thank you.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Bostonian
  • 615
  • 7
  • 16

2 Answers2

5

This is called object-private access modifier

Members marked private without a qualifier are called class-private, whereas members labeled with private[this] are called object-private.

and specifies the most restrictive access

The most restrictive access is to mark a method as “object-private.” When you do this, the method is available only to the current instance of the current object. Other instances of the same class cannot access the method.

More precisely, [this] part of private[this] is referred to as access qualifier:

AccessModifier    ::=  (‘private’ | ‘protected’) [AccessQualifier]
AccessQualifier   ::=  ‘[’ (id | ‘this’) ‘]’
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
1

private[this] takes the privacy to one step further and it makes the field object private. Unlike private, now the field cannot be accessed by other instances of the same type, making it more private than plain private setting.

For example,

class Person {
 private val name = "John"
 def show(p: Person) = p.name
}

(new Person).show(new Person) // result: John

class Person {
 private[this] val name = "John"
 def show(p: Person) = p.name // compilation error
}

After adding private[this], field can only be accessed by current instance not any other instance of class.

Mahesh Chand
  • 3,158
  • 19
  • 37