Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala automatic getter and setter overwriting with custom _=

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?

like image 935
valenterry Avatar asked Apr 08 '14 11:04

valenterry


1 Answers

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.

like image 171
Jean-Philippe Pellet Avatar answered Nov 24 '22 00:11

Jean-Philippe Pellet