Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is '_=' in scala?

Tags:

scala

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:

  1. why _age, why not age, is there any special benifit or just a convention to understand as private.

  2. what is _= in def age_=(newAge:Int) = _age = newAage what this statement doing.

like image 797
Sun Avatar asked Oct 15 '16 11:10

Sun


1 Answers

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 _= in def 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.

like image 136
Yuval Itzchakov Avatar answered Oct 11 '22 01:10

Yuval Itzchakov