在Scala中使用@BeanProperty而不是定义getter/setter函数是一种好习惯吗? [英] Is it good practice to use @BeanProperty in Scala instead of defining getter/setter functions?

查看:121
本文介绍了在Scala中使用@BeanProperty而不是定义getter/setter函数是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在可以公开访问/修改的类中定义数据成员

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生成这些注释使用注释.注释仅为这些方法添加getFoosetFoo别名.如果需要这些别名,请使用批注;如果不需要,请使用批注.

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.

总结最佳做法:

  1. 不要使用var.
  2. 如果必须使用var,则可以(并且应该)避免定义自己的getter和setter.
  3. 仅当您正在实现具有getFoosetFoo样式的方法签名的接口时,或者如果您希望从Java调用代码(使用诸如以下名称的调用方法)来使用BeanProperty批注foo_$eq不方便).
  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).

这篇关于在Scala中使用@BeanProperty而不是定义getter/setter函数是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆