0

If I have defined a variable b val b:B. Is it possible to print the value of b each time b is assigned to a new value. Like the code below:

  case class B(name:String) {
  }

  var b = B("123")
  b = B("xxx")
  println(s"b is changed to $b")

  b = B("xxJJx")
  println(s"b is changed to $b")

I hope the code println(s"b is changed to $b") be hidden in some sort of macro when I create B or b, like:

var b = macro_wrap(B("123"))
worldterminator
  • 2,968
  • 6
  • 33
  • 52
  • In Scala assignment operator [is not a method call](https://stackoverflow.com/questions/19086851/in-scala-is-assignment-operator-a-method-call), so def macros will not help. – Dmytro Mitin Jan 23 '19 at 09:43

1 Answers1

0

With plain var, you cannot do it.

The closest you can get is to create a getter-setter pair which will look like a var from outside:

object Stuff {
  private var b0 = B("123")
  def b: B = b0
  def b_=(newb: B): Unit = {
    b0 = newb
    println(s"b is changed to $newb")
  }
}

Then:

Stuff.b = B("xxx")

Will print the new value.

Note that the setter is a method named b_= which is treated somewhat specially by Scala compiler - an assignment Stuff.b = B("xxx") is automatically translated into Stuff.b_=(B("xxx")). This works only if setter is accompanied by a getter.

ghik
  • 10,706
  • 1
  • 37
  • 50