Mikaël Mayer
Mikaël Mayer

Reputation: 10701

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.

Upvotes: 1

Views: 152

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

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.

Upvotes: 3

iuriisusuk
iuriisusuk

Reputation: 434

you cannot override assignment operator, since it's a reserved word. what you can do is this:

object BAndA {
  var b: Map[String, Int] = Map()

  def a = b // getter
  def a_=(i: Int) = b += "method" -> i // setter
}

object Test extends App {
  import BAndA._

  a = 1
  println(b)
}

getter is requried

Upvotes: 0

Related Questions