You probably wanted to write setter but due to the wrong syntax you ended up with a variable visible from the outside AND weirdly named method:
val x = new Person()
x.age_(3)
x.age_(-10)
x.age
// Int = 3
Correct way of writing setter could be (note trailing =
in the method name):
class Person {
private var privateAge: Int = 0
def age_=(newAge: Int) {
if( newAge > 0 ) privateAge = newAge
}
def age = privateAge
}
val x = new Person()
x: Person = Person@42c08a7e
x.age = -10
// x.age: Int = 0
x.age
// res7: Int = 0