5.1. Controlling Method Scope

Problem

Scala methods are public by default, and you want to control their scope in ways similar to Java.

Solution

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:

  • Object-private scope

  • Private

  • Package

  • Package-specific

  • Public

These scopes are demonstrated in the examples that follow.

Object-private scope

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 modifier private[this] before the method declaration:

  private[this] def isFoo = true

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:

class Foo {

  private[this] def isFoo = true

  def doFoo(other: Foo) {
    if (other.isFoo) {  // 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.

Private scope

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

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.