5.6. Forcing Callers to Leave Parentheses off Accessor Methods

Problem

You want to enforce a coding style where getter/accessor methods can’t have parentheses when they are invoked.

Solution

Define your getter/accessor method without parentheses after the method name:

class Pizza {
  // no parentheses after crustSize
  def crustSize = 12
}

This forces consumers of your class to call crustSize without parentheses:

scala> val p = new Pizza
p: Pizza = Pizza@3a3e8692

// this fails because of the parentheses
scala> p.crustSize()
<console>:10: error: Int does not take parameters
              p.crustSize()
                            ^

// this works
scala> p.crustSize
res0: Int = 12

Note

Coming from a Java background, I originally named this method getCrustSize, but the Scala convention is to drop “get” from methods like this, hence the method name crustSize.

Discussion

The recommended strategy for calling getter methods that have no side effects is to leave the parentheses off when calling the method. As stated in the Scala Style Guide:

Methods which act as accessors of any sort ... should be declared without parentheses, except if they have side effects.

According to the style guide, because a simple accessor method like crustSize does not have side effects, it should not be called with parentheses, and this recipe demonstrates how to enforce this convention.

Although this recipe shows how to force callers to leave parentheses off methods when calling simple getters, there is no way to force them to use parentheses for side-effecting methods. ...

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.