Scala吸气器/设置器-最佳实践? [英] Scala getters/setters - best practice?

查看:60
本文介绍了Scala吸气器/设置器-最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java SE/EE开发人员,但还是Scala的初学者.在Java中,当我有一些私有字段可供其他代码访问时,我使用getX()/setX()经典的getter/setter方法.但是,不确定Scala怎么样.我注意到在Scala中,字段的getter/setter命名约定是使用与字段相同的名称.因此,只需设置字段public是否可以,还是应该使用这种类型的getter/setter方法?:

I'm Java SE/EE developer, but beginner in Scala. In Java, when I have some private fields which should be accessible to other code, I use getX()/setX() classic style of getters/setters. However, not sure how about Scala. I noticed that in Scala, naming convention of getter/setter for field is to use the same name as the field's one. So is it OK to simply set the field public, or should I use this style of getter/setter?:

private var _value = .....
def value = _value
def value_= (newVal:Int) = _value = newVal

在字段名称本身之前加下划线是否可以(按照Scala命名约定)?

Is it OK (according to scala naming convention) to put underscore before the field name itself?

谢谢.

推荐答案

Scala样式指南很好地涵盖了这一点.

The Scala Style Guide covers this quite nicely.

对于属性的访问者,方法的名称应为属性的名称.

For accessors of properties, the name of the method should be the name of the property.

Scala不遵循Java约定. Scala提出了这样一种观点,即调用者不应该知道字段访问和方法调用之间的区别,这意味着约定是给它们两个相同的名称.这样就减少了将字段更改为方法时所需的代码更改量,反之亦然.

Scala does not follow the Java convention. Scala promotes the view that a caller should not be able to tell the difference between a field access and a method call, which means that the convention is to give them both the same name; thus reducing the amount of code change required should a field be changed to a method or visa versa.

是否可以在字段名称本身之前加下划线(根据scala命名约定)?

Scala约定是为要私有的字段添加前缀,否则这些字段与公共方法具有相同的名称,或者将其后缀零.两种方法都可以接受.

Scala convention is to prefix fields that we want to be private that otherwise have the same name as a public method, or to postfix it with a zero. Either approach is acceptable.

private var _value = .....
def value = _value
def value_= (newVal:Int) = _value = newVal

但是,在此示例中,多余的行不是必需的.存在约定,以便我们可以使用此较短的版本,然后在需要时/以后将其更改为更显式的版本,而不必在每个呼叫站点进行更改.

However, given this example the extra lines are not necessary. The convention exists so that we can use this shorter version and then change it later to the more explicit version when/if we need to without having to make changes at every call site.

var value:Int = 0

这篇关于Scala吸气器/设置器-最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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