Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are accessor and mutator methods in Scala?

Tags:

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?

like image 666
RoyalCanadianKiltedYaksman Avatar asked Nov 16 '25 03:11

RoyalCanadianKiltedYaksman


1 Answers

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.

like image 155
gzm0 Avatar answered Nov 17 '25 19:11

gzm0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!