Following the JavaBean Convention

The accessors that the Scala compiler generates by default don’t conform to the JavaBean method naming conversion. This is not a big deal if your classes are used only from Scala. But, it’s rather undesirable if the classes are used from Java. That’s because, since both Java programmers and Java IDEs are so used to the JavaBean convention, the Scala style accessors would be confusing and hard to use from Java. Furthermore, most Java frameworks assume the JavaBean convention and not following that would make it hard to use Scala classes with those frameworks. No sweat—it’s an easy fix with an annotation.

Simply mark the desired field declarations with the scala.beans.BeanProperty annotation. Upon seeing this annotation the Scala compiler will faithfully generate the JavaBean-like accessors in addition to the Scala style accessors. And the Scala syntax for using annotations is much the same as in Java.

For example, we’ve marked one constructor parameter and the field declaration with the annotation in the following code:

WorkingWithObjects/Dude.scala
 
import​ scala.beans.BeanProperty
 
 
class​ Dude(@BeanProperty ​val​ firstName: ​String​, ​val​ lastName: ​String​) {
 
@BeanProperty ​var​ position: ​String​ = _
 
}

Using the annotation we instructed Scala to create the accessor methods getFirstName, getPosition, and setPosition, in addition to the Scala style accessors for the two parameters and the declared field. Since we did not mark the parameter lastName with the annotation, it does not get the JavaBean style accessor. We can see this by taking a peek at the generated code by running the commands:

 
scalac Dude.scala
 
javap -private Dude

Look at the output of javap to confirm your understanding of the effects of the annotation and how to create code that follows the JavaBean convention:

 
Compiled from "Dude.scala"
 
public class Dude {
 
private final java.lang.String firstName;
 
private final java.lang.String lastName;
 
private java.lang.String position;
 
public java.lang.String firstName();
 
public java.lang.String lastName();
 
public java.lang.String position();
 
public void position_$eq(java.lang.String);
 
public void setPosition(java.lang.String);
 
public java.lang.String getFirstName();
 
public java.lang.String getPosition();
 
public Dude(java.lang.String, java.lang.String);
 
}

If you mark all the primary constructor parameters and the fields with the BeanProperty annotation, then from Java you can use the JavaBean convention to access the properties of the class. This will make your fellow Java developers happy due to pleasant interoperability. At the same time, you can use either the JavaBean convention or—preferably—the Scala style to access the properties from Scala, as that’s more idiomatic and less noisy.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.141.206