Accessors and Mutators in Scala

Scala Tutorial

Senthil Nayagan
1 min readDec 17, 2018

Accessors are get methods and mutators are set methods. Scala does not follow the Java convention of prepending set/get to mutator and accessor methods respectively.

Accessor Convention

  • For accessors of most boolean and non-boolean properties, the name of the method should be the name of the property.
  • For accessors of some boolean properties and in the case of no corresponding mutator is provided, the name of the method may be the capitalized name of the property with “is” prepended (e.g. isEmpty).

Mutator Convention

  • The name of the method should be the name of the property with “_=” appended (e.g. def bar_=(bar: Bar) {..}) .

Preventing getter & setter methods being generated

We can add the private keyword to a val or var field to prevent getter and setter methods from being generated. The private fields could only be accessed from within members of the class.

class PreventGetterSetter(private var myField: String) {
// myField could only be accessed from within
// members of the class like below
def assesMyField = println(myField)
}

Defining a field as private limits the field so it’s only available to instances of the same class.

--

--

Senthil Nayagan
Senthil Nayagan

Written by Senthil Nayagan

I am a Data Engineer by profession, a Rustacean by interest, and an avid Content Creator.

No responses yet