每";塞特;方法需要一个";“吸气剂”;Scala中的方法?
Scala程序员应该知道这种书写方式:每";塞特;方法需要一个";“吸气剂”;Scala中的方法?,scala,syntax,setter,getter,Scala,Syntax,Setter,Getter,Scala程序员应该知道这种书写方式: 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
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方法defid=\u id
,p.id=2
将导致编译错误,即
error: value key is not a member of Person
有人能解释一下原因吗 编译器之所以如此,是因为规范这么说 见第页。86,§6.15转让 请注意,没有任何东西阻止您:
- 使getter
私有化
- 使getter返回另一个类型
- 将getter设置为“不可调用”,例如:
defid id(隐式no:Nothing)
x
是某个模板中定义的无参数函数,并且同一模板包含一个setter函数x
作为成员,那么赋值x=e
被解释为该setter函数的调用x=(e)
。”这要求x
是一个无参数函数。事实上,至少在2.10.4中,getter不能是私有的。不过,第三个技巧(隐式no:Nothing
)有效。您对Person
的两个定义并不完全相同,因为第二个技巧还将为\u id
生成私有getter和setter方法。