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:

  1. don't use var.
  2. if have use var, can (and should) avoid defining own getters , setters.
  3. use beanproperty annotation if you're implementing interface getfoo , setfoo-style method signatures, or if you're expecting code called java (where calling methods names foo_$eq inconvenient).

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -