javabeans - Is it good practice to use @BeanProperty in Scala instead of defining getter/setter functions? -
defining data members in class can publicly accessed/modified
var _foo: int = _ def foo_(foo: int) = _foo = foo    // setter function def foo = _foo                     // getter function   is practice convert using annotation @beanproperty?
import scala.reflect.beanproperty @beanproperty var foo: int = _   and when use annotation , when not to?
there's redundancy in first example, since defining var results in generation of getters , setters. example, if compile class:
class foo {   var foo: int = _ }   then javap -private foo shows following:
public class foo {   private int foo;   public int foo();   public void foo_$eq(int);   public foo(); }   unless have custom logic need fit getters or setters (in case it's idea consider more descriptive method names, anyway), shouldn't need define them manually.
the scala.reflect.beanproperty annotation (or scala.beans.beanproperty on 2.11) doesn't have effect on generation of foo() , foo_$eq(int) methods—the compiler generate these var foo: int whether or not use annotation. annotation adds getfoo , setfoo aliases these methods. if need these aliases, use annotation, , if don't, don't.
to summarize best practices:
- don't use 
var. - if have use 
var, can (and should) avoid defining own getters , setters. - use 
beanpropertyannotation if you're implementing interfacegetfoo,setfoo-style method signatures, or if you're expecting code called java (where calling methods namesfoo_$eqinconvenient). 
Comments
Post a Comment