Thursday, January 28, 2016

Scala Getter/Setter and BeanProperties

Scala provides automatic getter/setter functions for class data members After compiling this piece of code using Scala compiler scalac
scalac Foo.scala
Generates Foo.class file which we can disassemble using Java class file disassembler program javap https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javap.html
javap -private Foo.class
Disassembling class file shows
public class Foo {
  private int foo;
  public int foo();
  public void foo_$eq(int);
  public Foo();
}
Here we can see int foo() returns foo value and foo_$eq(int) assigns the value to private int foo (works like a setter). Which means we do not have to define private data member, getter and setter explicitly like;
private var _foo: Int = _
def foo_=(foo: Int) = _foo = foo    // setter
def foo = _foo    // getter
Instead, we can only declare
var foo: Int = _
On the other hand, Scala provides an annotation @BeanProperty which you can use to declare automatic getter/setter functions. To define a data member as a bean property you just have to write @BeanProperty before declaring member variable
import scala.reflect.BeanProperty
@BeanProperty var foo: Int = _
This should be implemented when you call Scala code from Java. Java libraries and APIs expect a class getter/setter function names as getMember/setMember. @BeanProperty generates these getter/setter functions too. That is why it is feasible to use @BeanProperty instead of simple public variable declaration when intermixing Java with Scala.

No comments :

Post a Comment