There's some redundancy in your first example, since defining a var
already results in the generation of getters and setters. For example, if we compile this class:
class Foo {
var foo: Int = _
}
Then javap -private Foo
shows the following:
public class Foo {
private int foo;
public int foo();
public void foo_$eq(int);
public Foo();
}
Unless you have custom logic that you need to fit into your getters or setters (in which case it's often a good idea to consider more descriptive method names, anyway), you shouldn't need to define them manually.
The scala.reflect.BeanProperty
annotation (or scala.beans.BeanProperty
on 2.11) doesn't have any effect on the generation of the foo()
and foo_$eq(int)
methods—the compiler will generate these for a var foo: Int
whether or not you use the annotation. The annotation simply adds getFoo
and setFoo
aliases for these methods. If you need these aliases, use the annotation, and if you don't, don't.
To summarize best practices:
- Don't use
var
.
- If you have to use
var
, you can (and should) avoid defining your own getters and setters.
- Use the
BeanProperty
annotation only if you're implementing an interface with getFoo
and setFoo
-style method signatures, or if you're expecting your code to be called from Java (where calling methods with names like foo_$eq
is inconvenient).