5.3 Properties with Only Getters
Sometimes you want a read-only property with a getter but no setter. If the value of the property never changes after the object has been constructed, use a val field:
class Message { val timeStamp = java.time.Instant.now ... }
The Scala compiler produces a Java class with a private final field and a public getter method, but no setter.
Sometimes, however, you want a property that a client can’t set at will, but that is mutated in some other way. The Counter class from Section 5.1, “Simple Classes and Parameterless Methods,” on page 55 is a good example. Conceptually, the counter has a current property that is updated when the increment method is called, but there is no setter for the property.
You can’t implement such a property with a val—a val never changes. Instead, provide a private field and a property getter, like this:
class Counter { private var value = 0 def increment() { value += 1 } def current = value // No () in declaration }
Note that there are no () in the definition of the getter method. Therefore, you must call the method without parentheses:
val n = myCounter.current // Calling myCounter.current() is a syntax error
To summarize, you have four choices for implementing properties:
var foo: Scala synthesizes a getter and a setter.
val foo: Scala synthesizes a getter.
You define methods foo and foo_=.
You define a method foo.