Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding setter on var

Tags:

scala

A tiny question with hopefully a tiny answer:

I have a var in my class that needs to trigger some kind of update whenever it is set. I know that a var implicitly gets two methods with it, a getter and a setter. Is it possible to somehow override the setter method to make sure the update is triggered, without getting recursive? I mean

def a_=(x: Any) = { a = x; update }

Will probably be an infinite recursion, right?

The var is only set outside the class and read only inside the class, maybe that helps.

Thanks for listening.

like image 543
Lanbo Avatar asked Feb 13 '11 19:02

Lanbo


1 Answers

Your code will never be an infinite recursion because it won't compile. Due to implicit creation of a Getter and a Setter by the compiler you can't create such methods twice. I don't know if there is a reason why the compiler does not check if a Getter or a Setter exists and only if there are no such methods it create ones.

You can avoid this problem by renaming the private variable:

class X(private var _i: Int) {
  def i = _i
  def i_=(i: Int) {
    println(i)
    _i = i
  }
}

These methods have the same signature as the methods generated by the compiler.

If the update method has only be called once you can do this inside the companion object:

object X {
  def apply(i: Int) = {
    update
    new X(i)
  }
}
class X(i: Int)

Is there a reason why you don't prefer an immutable object? If no, you can copy the old one and set a new value at the same time:

case class X(i: Int, j: Int)
val x1 = X(3, 6)
val x2 = x1.copy(i = 1) // x2 = X(1,6)
like image 164
kiritsuku Avatar answered Sep 26 '22 06:09

kiritsuku