5.5 Bean Properties
As you saw in the preceding sections, Scala provides getter and setter methods for the fields that you define. However, the names of these methods are not what Java tools expect. The JavaBeans specification (www.oracle.com/technetwork/articles/javaee/spec-136004.html) defines a Java property as a pair of getFoo/setFoo methods (or just a getFoo method for a read-only property). Many Java tools rely on this naming convention.
When you annotate a Scala field with @BeanProperty, then such methods are automatically generated. For example,
import scala.beans.BeanProperty
class Person { @BeanProperty var name: String = _ }
generates four methods:
name: String
name_=(newValue: String): Unit
getName(): String
setName(newValue: String): Unit
Table 5–1 shows which methods are generated in all cases.
Table 5–1 Generated Methods for Fields
Scala Field |
Generated Methods |
When to Use |
val/var name |
public name |
To implement a property that is publicly accessible and backed by a field. |
@BeanProperty val/var |
public name |
To interoperate with JavaBeans. |
private val/var name |
private name |
To confine the field to the methods of this class, just like in Java. Use private unless you really want a public property. |
private[this] val/var |
none |
To confine the field to methods invoked on the same object. Not commonly used. |
private[ClassName] |
implementationdependent |
To grant access to an enclosing class. Not commonly used. |