由于使用私有 [this] 而不是私有,行为上的意外差异似乎 [英] Unexpected difference in behavior seemingly due to using private[this] instead of private
问题描述
这两个类的行为不同;原因似乎与使用 private[this]
声明而不是 private
相关.有人能解释一下原因吗?
These two classes behave differently; the cause seems related to the use of a private[this]
declaration instead of a private
. Can somebody explain why, please?
私有
:
class Person(
private var _age: Int
) {
if (_age < 0) { _age = 0 }
def age = _age
def age_=(newAge: Int) {
if (newAge > _age) { _age = newAge }
}
}
在 REPL 中,这与我对两个类所期望的一样;即age
方法得到_age
,在构造时已经设置为合适的值:
In the REPL, this behaves as I was expecting for both classes; that is, the age
method gets _age
, which has been set to the appropriate value during construction:
scala> val person = new Person(-1)
person: Person = Person@200a570f
scala> person.age
res0: Int = 0
private[this]
:
class Person(
private[this] var _age: Int
) {
if (_age < 0) { _age = 0 }
def age = _age
def age_=(newAge: Int) {
if (newAge > _age) { _age = newAge }
}
}
在 REPL 中,person.age
似乎在对 if
表达式求值之前取 _age
的值.不过,在使用 setter 后,它按预期工作:
In the REPL, person.age
appears to take the value of _age
prior to the evaluation of the if
expression. It works as expected after using the setter, though:
scala> val person = new Person(-1)
person: Person = Person@6f75e721
scala> person.age
res0: Int = -1
scala> person.age = 0
person.age: Int = 0
scala> person.age
res1: Int = 0
推荐答案
这是一个已知的错误,即 SI-6880.
This is a known bug, namely SI-6880.
这篇关于由于使用私有 [this] 而不是私有,行为上的意外差异似乎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!