Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Every "setter" method requires a "getter" method in Scala?

Scala programmer should have known that this sort of writing :

class Person{
   var id  = 0 
}
var p = new Person 
p.id 
p.id = 2    

equals to

class Person{
private var _id = 0 
def id = _id
def id_=(i: Int) = _id = i
}
val p = new Person 
p.id // be equal to invoke id method of class Person
p.id = 2   // be equal to p.id_=(2) 

in effect. But if you comment the getter method def id = _id , p.id = 2 will cause a compilation error, saying

error: value key is not a member of Person 

Could anyone explain why ?

like image 994
爱国者 Avatar asked Apr 06 '12 08:04

爱国者


1 Answers

The compiler is so because the specification says so.

See the Scala Reference, p. 86, §6.15 Assignments.

Note that nothing prevents you from:

  • making the getter private
  • making the getter return another type
  • making the getter “uncallable”, e.g. like this: def id(implicit no: Nothing)
like image 67
Jean-Philippe Pellet Avatar answered Oct 19 '22 07:10

Jean-Philippe Pellet