Scala automatic getter and setter overwriting with

2020-07-13 11:18发布

问题:

In scala there is no difference for the user of a class between calling a method or accessing some field/member directly using val x = myclass.myproperty. To be able to control e.g. setting or getting a field, scala let us override the _= method. But is = really a method? I am confused.

Let's take the following code:

class Car(var miles: Int)

var myCar = new Car(10)
println(myCar.miles) //prints 10
myCar.miles = 50
println(myCar.miles) //prints 50

Same goes for this code (notice the double space in myCar.miles = 50):

class Car(var miles: Int)

var myCar = new Car(10)
println(myCar.miles) //prints 10
myCar.miles  = 50
println(myCar.miles) //still prints 50

Now i want to change the way how the miles can be set or read, e.g. always printing something on the screen. How can i do this so that the users of my class are not affected and also so that it does not make any difference if whitespaces are used before the = sign?

回答1:

Try this:

class Car(private var _miles: Int) {
  def miles = _miles
  def miles_=(m: Int): Unit = {
    println("boo")
    _miles = m
  }
}

Whitespace is not significant. The compiler sees you're assigning miles and will insert a call to miles_= no matter how many spaces you insert.