What are accessor and mutator methods in Scala?

These are apparently generated in scala automatically for any parameters in constructors (which I suppose also implies that they can be added manually somewhere else) but what are these things?

Upvotes: 4

Views: 3250

Answers (1)

gzm0
gzm0

Reputation: 14842

Accessor and mutator methods are normal methods with special names. Look at the following example:

class A {
  var x: Int = _
}

Is the same as (as in "the compiler generates the following"):

class A {
  private[this] var internal: Int = _
  // this is the accessor
  def x: Int = internal 
  // this is the mutator
  def x_=(x: Int): Unit = internal = x
}

When you write or read x, the following happens:

val a: A = ???
println(a.x) // -> method x on A is called
a.x = 1 // syntactic sugar for a.x_=(1)

The nice thing about this is, that you can change a var at a later point in time to include, say, consistency checks:

class A {
  private[this] var _x: Int = _
  def x: Int = _x 
  def x_=(x: Int): Unit = {
    if (x < 0)
      throw new IllegalArgumentException("Must be non-negative")
    _x = x
  }
}

The ability to replace variables by accessors/mutators transparently is also known as uniform access principle.

Upvotes: 9

Related Questions