Reputation: 10701
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
Reputation: 369458
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.
Upvotes: 3
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