john john - 3 months ago 8
Scala Question

Scala: the diffenence of method with brackets and not

class Person {
private var privateAge = 0
def age() = {privateAge}
def age_=(age:Int) {privateAge=age}
}

object Main{
def main(args:Array[String]){
val p = new Person
p.age = 12
}
}


When compile,
p.age = 12
raise issue: reassignment to val

While if i remove the brackets of
def age() = {privateAge}
in Person class, it works fine.

I confused that the
p.age = 12
method should corresponds to
def age_=(age:Int) {privateAge=age}
, but why i changed the
def age() = {privateAge}
, it works.

Answer

You cannot define a setter-only property. Scala only recognizes a setter when it is paired with a corresponding getter. A getter is method with no parameter list, and a setter is a method whose name ends in _= with a single parameter list that takes a single argument of the return type of the getter method and returns Unit.

In your code, you don't have getter method: age is not a getter because it has a parameter list. Note: an empty parameter list is not the same thing as no parameter list, just like an empty house is not the same thing as no house.