Home > Articles

  • Print
  • + Share This
This chapter is from the book

5.5 Bean Properties l1.jpg

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:

  1. name: String

  2. name_=(newValue: String): Unit

  3. getName(): String

  4. 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
name_= (var only)

To implement a property that is publicly accessible and backed by a field.

@BeanProperty val/var
name

public name
getName()
name_= (var
only)
setName(...) (var only)

To interoperate with JavaBeans.

private val/var name

private name
name_= (var only)

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
name

none

To confine the field to methods invoked on the same object. Not commonly used.

private[ClassName]
val/var name

implementationdependent

To grant access to an enclosing class. Not commonly used.

  • + Share This
  • 🔖 Save To Your Account