4.7. Preventing Getter and Setter Methods from Being Generated
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.
Solution
Define the field with the private or private[this] access modifiers, as shown with
the currentPrice field in this
example:
classStock{// getter and setter methods are generatedvardelayedPrice:Double=_// keep this field hidden from other classesprivatevarcurrentPrice:Double=_}
When you compile this class with scalac, and then disassemble it with javap, you’ll see this interface:
// Compiled from "Stock.scala"publicclassStockextendsjava.lang.Objectimplementsscala.ScalaObject{publicdoubledelayedPrice();publicvoiddelayedPrice_$eq(double);publicStock();}
This shows that getter and setter methods are defined for the
delayedPrice field, and there are no
getter or setter methods for the currentPrice field, as desired.
Discussion
Defining a field as private
limits the field so it’s only available to instances of the same class,
in this case instances of the Stock
class. To be clear, any instance of a Stock class can access a private field of any
other Stock instance.
As an example, the following code yields true when the Driver object is run, because the isHigher method in the Stock class can access the price field both (a) in its object, and (b) in
the other Stock ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access