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?
private:
class Person(
private var _age: Int
) {
if (_age < 0) { _age = 0 }
def age = _age
def age_=(newAge: Int) {
if (newAge > _age) { _age = newAge }
}
}
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 }
}
}
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
This is a known bug, namely SI-6880.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With