重写局部变量赋值
Rewrite local var assignment in
我想用 Scala 写这个:
var b: Map[String, Int] = Map()
def method() = {
def a_=(i: Int) = b += "method" -> i
// ...
a = 2
}
但这会抱怨说 a 没有定义。这是为什么?我以为 a = ...
被重写为 a_=(...)
.
解决方案:感谢 Jörg,我的工作,必须提供 getter 并使方法成为顶级:
var b: Map[String, Int] = Map()
def a_=(i: Int) = b += "method" -> i
def a: Int = ??? // Dummy
def method() = {
// ...
a = 2
}
编译成功。
您不能覆盖赋值运算符,因为它是一个保留字。你可以做的是:
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 需要
Why is that? I thought a = ...
was rewritten to a_=(...)
.
没有
- 您需要 getter 和 一个 setter 才能使重写生效。
- 只有当有东西要重写时才会重写,即
object
、class
或 trait
. 的字段访问
参见section 6.15 Assignments of the Scala Language Specifiation(粗体强调我的):
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.
我想用 Scala 写这个:
var b: Map[String, Int] = Map()
def method() = {
def a_=(i: Int) = b += "method" -> i
// ...
a = 2
}
但这会抱怨说 a 没有定义。这是为什么?我以为 a = ...
被重写为 a_=(...)
.
解决方案:感谢 Jörg,我的工作,必须提供 getter 并使方法成为顶级:
var b: Map[String, Int] = Map()
def a_=(i: Int) = b += "method" -> i
def a: Int = ??? // Dummy
def method() = {
// ...
a = 2
}
编译成功。
您不能覆盖赋值运算符,因为它是一个保留字。你可以做的是:
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 需要
Why is that? I thought
a = ...
was rewritten toa_=(...)
.
没有
- 您需要 getter 和 一个 setter 才能使重写生效。
- 只有当有东西要重写时才会重写,即
object
、class
或trait
. 的字段访问
参见section 6.15 Assignments of the Scala Language Specifiation(粗体强调我的):
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.