1
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.

john
  • 67
  • 3
  • Possible duplicate of [Use of def, val, and var in scala](http://stackoverflow.com/questions/4437373/use-of-def-val-and-var-in-scala) –  Aug 15 '16 at 03:13

2 Answers2

2

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
0

this is how custom assignment is defined in the spec:

If x is a parameterless function defined in some template, and the same template contains a setter function x_= as member, then the assignment x = e is interpreted as the invocation x_=(e) of that setter function. Analogously, an assignment f.x = e to a parameterless function x is interpreted as the invocation f.x_=(e).

(from http://scala-lang.org/files/archive/spec/2.11/06-expressions.html#assignments)

"parameterless" methods are defined here: http://www.scala-lang.org/files/archive/spec/2.11/03-types.html#method-types

handler
  • 1,463
  • 11
  • 11
  • No, for "parameterless" see http://www.scala-lang.org/files/archive/spec/2.11/03-types.html#method-types and the other answer. – som-snytt Aug 15 '16 at 03:39
  • Can you explain why the "reassignment to val" error appears if the parentheses are used in age()? Is it because age() returns the value of privateAge and so an int value cant be reassigned to another int value? – Samar Aug 15 '16 at 03:58
  • @Samar see the other answer. Getter can't have parens. That's why `toString` can't be a property even if `def toString_=(s: String) = ???`. – som-snytt Aug 15 '16 at 04:40
  • got it. The usage of same method as getter and setter depending on context (assignment vs simple calling).. didn't know this before. Scala authors go to great lengths to allow brevity of language. – Samar Aug 15 '16 at 04:59