I am learning Scala but I am having difficulty understanding it. I got some Scala code in one of the tutorial, but I am not able to understand a few things.
This is the code:
class Person(val id:Int,
var firstName:String,
var lastName:String,
private var _age:Int) {
// these methods are identical to what would be created by var in the constructor
def age = _age
def age_=(newAge:Int) = _age = newAage
}
val me = new Person(45,"Dave","Copeland",35)
me.firstName = "David"
me.age = 36
I did not understand:
why _age
, why not age
, is there any special benifit or just a convention to understand as private.
what is _=
in def age_=(newAge:Int) = _age = newAage
what this statement doing.
That is the way to declare getters and setters in Scala.
why _age, why not age, is there any special benefit or just a convention to understand as private.
Because age
is already taken by the getter declaration, so you need an alternative variable name.
what is
_=
indef age_=(newAge: Int) = _age = newAge
what this statement doing.
It is a hint to the compiler that this is a setter method. Externally, age will be exposed as a property which you can call like this:
val p = new Person(1, "a", "b", 10)
p.age = 42
println(p.age)
You don't explicitly invoke age_=
, but the setter method will still get called. Same goes for getter.
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