在Scala中使用@BeanProperty而不是定义getter/setter函数是一种好习惯吗? [英] Is it good practice to use @BeanProperty in Scala instead of defining getter/setter functions?
问题描述
在可以公开访问/修改的类中定义数据成员
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
使用注释@BeanProperty
进行转换是否是一个好习惯?
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?
推荐答案
在您的第一个示例中有一些冗余,因为定义var
已经导致生成getter和setter.例如,如果我们编译此类:
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 = _
}
然后javap -private Foo
显示以下内容:
public class Foo {
private int foo;
public int foo();
public void foo_$eq(int);
public Foo();
}
除非您有需要适应getter或setter方法的自定义逻辑(在这种情况下,考虑使用更具描述性的方法名通常是个好主意),否则您无需手动定义它们.
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.
scala.reflect.BeanProperty
批注(或2.11中的scala.beans.BeanProperty
)对foo()
和foo_$eq(int)
方法的生成没有任何影响-编译器将为var foo: Int
生成这些注释使用注释.注释仅为这些方法添加getFoo
和setFoo
别名.如果需要这些别名,请使用批注;如果不需要,请使用批注.
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.
总结最佳做法:
- 不要使用
var
. - 如果必须使用
var
,则可以(并且应该)避免定义自己的getter和setter. - 仅当您正在实现具有
getFoo
和setFoo
样式的方法签名的接口时,或者如果您希望从Java调用代码(使用诸如以下名称的调用方法)来使用BeanProperty
批注foo_$eq
不方便).
- 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 withgetFoo
andsetFoo
-style method signatures, or if you're expecting your code to be called from Java (where calling methods with names likefoo_$eq
is inconvenient).
这篇关于在Scala中使用@BeanProperty而不是定义getter/setter函数是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!