5.1. Controlling Method Scope
Scala methods are public by default, and you want to control their scope in ways similar to Java.
Scala lets you control method visibility in a more granular and powerful way than Java. In order from “most restrictive” to “most open,” Scala provides these scope options:
These scopes are demonstrated in the examples that follow.
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.
You mark a method as object-private by placing the access
private[this] before the
In the following example, the method
doFoo takes an instance of a
Foo object, but because the
isFoo method is declared as an
object-private method, the code won’t compile:
// this line won't compile
The code won’t compile because the current
Foo instance can’t access the
isFoo method of the
other instance, because
isFoo is declared as
private[this]. As you can see, the
object-private scope is extremely restrictive.
A slightly less restrictive access is to mark a method
private, which makes the method available to (a) the current class and (b) other instances of the current class. ...