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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top