object-private

How to control Scala method scope with private, package, and more

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 5.1, “How to control method scope in Scala (private, package, more).”

Back to top

Problem

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

Back to top

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:

Table of Contents

  1. Problem
  2. Solution
Back to top

How to prevent getter and setter methods from being generated in Scala classes

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 4.7, “How to prevent getter and setter methods from being generated in Scala classes.”

Problem

When you define a class field as a var, Scala automatically generates getter and setter methods for the field, and defining a field as a val automatically generates a getter method, but you don’t want either a getter or setter.