问题
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
Is it OK (according to scala naming convention) to put underscore before the field name itself?
Thank you.
回答1:
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 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.
Is it OK (according to scala naming convention) to put underscore before the field name itself?
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
回答2:
According to the Scala docs:
Scala does not follow the Java convention of prepending set/get to mutator and accessor methods (respectively). Instead, the following conventions are used:
- For accessors of properties, the name of the method should be the name of the property.
- In some instances, it is acceptable to prepend “
is
” on a boolean accessor (e.g. isEmpty). This should only be the case when no corresponding mutator is provided. - For mutators, the name of the method should be the name of the property with “_=” appended.
Example:
class Foo {
def bar = ...
def bar_=(bar: Bar) {
...
}
def isBaz = ...
}
来源:https://stackoverflow.com/questions/26012039/scala-getters-setters-best-practice