Scala getters / setters best practice?

I am a Java SE / EE developer but new to Scala. In Java, when I have some private fields that need to be accessed by other code, I use the getX()

/ setX()

classic getters / setters style. Not sure how about Scala though. I noticed that in Scala the naming convention for getter / setter for a field is to use the same name as the field. So is this ok, just set the field public

, or should I use this getter / setter style ?:

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

      

Is it correct (according to scala naming convention) to put an underscore in front of the field name?

Thank.

+3


source to share


2 answers


The Scala Style Guide covers this pretty well.

For property accessories, the method name must be the name of the property.

Scala doesn't follow the Java convention. Scala promotes the notion that the caller shouldn't tell the difference between accessing a field and calling a method, which means that the convention should give them the same name; thus reducing the required number of code changes if the field is changed to a method or vice versa.

Is it good (according to Scala naming convention) to put an underscore in front of a field name?



Scala convention is to prefix the fields we want to be private, which otherwise have the same name as the public method, or postfixed with zero. Any approach is acceptable.

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

      

However, given this example, no additional lines are needed. The convention is such that we can use this shorter version and then later change it to a more explicit version if / if we need to, so as not to make changes at every call site.

var value:Int = 0

      

+15


source


According to the Scala docs :

Scala does not follow the Java convention of offering set / get to mutator and accessor methods (respectively). Instead, the following conventions are used:

  • For property accessories, the method name must be the name of the property.
  • In some cases, it is acceptable to add " is

    " in a boolean accessor (eg isEmpty). This should only be the case if an appropriate mutator is not provided.
  • For mutators, the method name must be a property name with "_ =" appended.


Example:

class Foo {
  def bar = ...
  def bar_=(bar: Bar) {
    ...
  }
  def isBaz = ...
}

      

+4


source







All Articles