scalavariable-assignmentrewriting

Rewrite local var assignment in


I would like to write this in Scala:

var b: Map[String, Int] = Map()
def method() = {
  def a_=(i: Int) = b += "method" -> i
  // ...
  a = 2
}

But this complains saying that a is not defined. Why is that? I thought a = ... was rewritten to a_=(...).

Solution: Thanks to Jörg, i works, one has to provide the getter and make the method top-level:

var b: Map[String, Int] = Map()
def a_=(i: Int) = b += "method" -> i
def a: Int = ??? // Dummy
def method() = {
  // ...
  a = 2
}

This compiles.


Solution

  • Why is that? I thought a = ... was rewritten to a_=(...).

    No.

    1. You need both a getter and a setter for the re-write to take effect.
    2. The re-write only happens when there is something to re-write, i.e. field access of an object, class, or trait.

    See section 6.15 Assignments of the Scala Language Specifiation (bold emphasis mine):

    If x is a parameterless function defined in some template, and the same template contains a setter function x_= as member, then the assignment x = e is interpreted as the invocation x_=(e) of that setter function.