Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
每";塞特;方法需要一个";“吸气剂”;Scala中的方法?_Scala_Syntax_Setter_Getter - Fatal编程技术网

每";塞特;方法需要一个";“吸气剂”;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

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 = 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)

你的回答让我很高兴:-)我不明白规范的这一部分如何需要getter才能让setter工作。您(或任何其他人)能解释一下吗?“如果
x
是某个模板中定义的无参数函数,并且同一模板包含一个setter函数
x
作为成员,那么赋值
x=e
被解释为该setter函数的调用
x=(e)
。”这要求
x
是一个无参数函数。事实上,至少在2.10.4中,getter不能是私有的。不过,第三个技巧(
隐式no:Nothing
)有效。您对
Person
的两个定义并不完全相同,因为第二个技巧还将为
\u id
生成私有getter和setter方法。