Scala Learning Series
Object-Private in Scala
Scala Programming
Dec 26, 2018
Defining fields and methods as private[this]
takes the privacy a step further and makes the field object-private which means that they can only be accessed from the object that contains them. A definition labeled private[this]
is accessible only from within the same object that contains the definition, making it more private than the plain private
. Other instances of the same class cannot access them!
Syntax
private[this] def isMaxVal = true
Example
class Cat {
var breed: String = "Persian"
private[this] var sex: String = "Male"
def showDetails(other: Cat): Unit = {
println(other.breed)
// Below statement won't compile as we are accessing
// via other instance of the same class.
//println(other.sex)
}
}