In Scala I see such feature as object-private variable. From my not very rich Java background I learnt to close everything (make it private) and open (provide accessors) if
To elaborate on the performance issue Alexey Romanov has mentioned, here are some of my guesses. Quotes from book "Programming in Scala: A Comprehensive Step-by-Step Guide, 2nd Edition" Section 18.2:
In Scala, every var that is non-private member of some object implicitly defines a getter and a setter method with it.
To test it out, this code will cause compilation error:
class PrivateTest{
var data: Int = 0
def data_=(x : Int){
require(x > 0)
data = x
}
}
Scala complains about error: ambiguous reference to overloaded definition. Adding override keyword to data_= won't help should prove that the method is generated by the compiler. Adding private keyword to variable data will still cause this compilation error. However, the following code compiles fine:
class PrivateTest{
private[this] var data: Int = 0
def data_=(x : Int){
require(x > 0)
data = x
}
}
So, I guess private[this] will prevent scala from generating getter and setter methods. Thus, accessing such variable will save the overhead of calling the getter and setter method.