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.
Why is that? I thought
a = ...
was rewritten toa_=(...)
.
No.
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 functionx_=
as member, then the assignmentx = e
is interpreted as the invocationx_=(e)
of that setter function.