I have a class with getter/setter:
class Person {
private var _age = 0
//getter
def age = _age
//setter
def age_=(value: Int): Unit = _age = value
}
We know that we can invoke setter method like this:
val p = new Person()
p.age= (2)
p age= 11
p.age= 8-4
What made interesthing in this case is: the underscore (_
) in def age_=
can be removed when the method is invoked.
My question is what is the underscore used for in this case?
Someone told me it is used to separate non-alphanum character in identifier. So I tried this:
var x_= = 20
x_= = 10
x= = 5 // I got error here
Why I can't remove the underscore in this case?
Also, if I tried to use the underscore more than once:
val x_=_x = 1
I got compile error too.
Is there a rule about the underscore usage and what is the term for this underscore usage?