What is the "_ =" in scala?

I study Scala, but it is difficult for me to understand this. I got the Scala code in one of the lessons, but I can’t 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 an agreement to understand as personal.

  • that is, _=in def age_=(newAge:Int) = _age = newAage making this expression.

+4
source share
1 answer

This is a way to declare getters and setters in Scala.

why _age, why not age, is there any particular advantage or just an agreement that can be understood as personal.

Since it is agealready used by the getter declaration, you need the name of an alternative variable.

_= def age_=(newAge: Int) = _age = newAge .

, setter. , :

val p = new Person(1, "a", "b", 10)
p.age = 42
println(p.age)

age_=, - . getter.

+9

Source: https://habr.com/ru/post/1657855/


All Articles