斯卡拉程序员应该已经知道,这种写作:每个“setter”方法都需要在Scala中使用“getter”方法吗?
class Person{
var id = 0
}
var p = new Person
p.id
p.id = 2
等于
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)
生效。但是,如果你对此有何评论getter方法def id = _id
,p.id = 2
会导致编译错误,说
error: value key is not a member of Person
谁能解释一下为什么?
'Person'的两个定义并不完全相同,因为第二个定义也会为'_id'生成私有getter和setter方法。 – 2012-04-06 08:44:41