Defining data members in a class that can be publicly accessed/modified
var _foo: Int = _
def foo_(foo: Int) = _foo = foo // setter function
def foo = _foo // getter function
Is it a good practice to convert this using annotation @BeanProperty
?
import scala.reflect.BeanProperty
@BeanProperty var foo: Int = _
and when to use this annotation and when not to?
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:
var
.var
, you can (and should) avoid defining your own getters and setters.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).@BeanProperty
is meant for Java interoperability, in particular with reflection-based Java frameworks expecting get
and set
methods.
Do not use it if you're staying in the Scala world. Use Scala getters (def foo
) and setters (def foo_=
) instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With