Search code examples
javascalanaming-conventions

Scala getters/setters - best practice?


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.


Solution

  • 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