Is it good practice to use @BeanProperty in Scala instead of defining getter/setter functions?

只愿长相守 提交于 2019-12-05 10:48:15

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:

  1. Don't use var.
  2. If you have to use var, you can (and should) avoid defining your own getters and setters.
  3. 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).

@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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!