Skip to content
Related Articles

Related Articles

Improve Article

Overriding Accessors and Mutators in Scala

  • Last Updated : 19 Sep, 2019

A standardized way to override default Accessors and Mutators hasn’t been fixed by Scala, yet users of this programming language use one specific and a common method for overriding which is discussed in detail below.

Before we get started, what are Accessors and Mutators?
Accessors and Mutators simply can be said as get and set methods respectively. Accessors are used for accessing the data by using variables or constants, helping a user to retrieve the information, working similar to a ‘Get’ method in Java and Mutators, meaning to change, wherein the variables are changed by a call to function and assigned a new value, they work analogus to ‘Set’ method in Java.

Consider the following Java code using set and get methods for a class Employee:

public class Employee {
    private String name;
    public String getName() {
        return name;
    public void setName(String name) { = name;

If you try to write a code for a class named Employee with a constructor parameter named ‘name’ and attempt to create get and set methods, according to the Scala conventions, your code won’t compile.

// error: this won't work
class Employee(private var name: String) {
  def name = name
  def name_=(aName: String) { name = aName }

On compilation of this code, following errors are produced:

Person.scala:3: error: overloaded method name needs result type
def name = name
Person.scala:4: error: ambiguous reference to overloaded definition,
both method name_= in class Employee of type (aName: String)Unit
and method name_= in class Employee of type (x$1: String)Unit
match argument types (String)
def name_=(aName: String) { name = aName }
Person.scala:4: error: method name_= is defined twice
def name_=(aName: String) { name = aName }
three errors found

The Scala compiler complains about the collision of the names between the ‘name’ field and the ‘name’ method. A simple way to solve this error is to add a underscore to the field variable. This resolves the ambiguity.

Note: The underscore is used in prefix position rather than suffix position to avoid any danger of mistakenly typing ‘name _’ instead of ‘name_’. A mistake in typing the other way round could potentially lead to a very confusing error since the heavy use of Scala’s type inference.

class Employee(private var _name: String) {
  def name = _name                             // accessor
  def name_=(aName: String) { _name = aName }  // mutator

How to call the constructor methods are as follows:

val e = new Employee("Adelicia") = "Alice"    // setter
println(    // getter

There are other approaches too for naming getter and setter methods.

Go Premium (An Ad Free Experience with many more features)

My Personal Notes arrow_drop_up
Recommended Articles
Page :