Scala:不能写setter没有getter?
这工作:
class ButtonCountObserver { private var cnt = 0 // private field def count = cnt // reader method def count_=(newCount: Int) = cnt = newCount // writer method // ... } val b = new ButtonCountObserver b.count = 0 但这不是 class ButtonCountObserver { private var cnt = 0 // private field def count_=(newCount: Int) = cnt = newCount // writer method // ... } val b = new ButtonCountObserver b.count = 0 我得到:错误:值计数不是ButtonCountObserver的成员 是否有可能创建一个setter(使用语法糖)没有getter? 解决方法
规范要求setter和getter都被定义为能够使用语法糖来调用setter:
此外,为了使用设定器,吸气剂必须是可见的。我不知道如果这是指定 Getter不可见#1 // error: method x cannot be accessed in x.Test object x { class Test { private[this] var x0: Int = 0 private[Test] def x = x0 def x_=(a: Int) = x0 = a } val t = new Test t.x = 1 } Getter不可见#2 //<console>:11: error: type mismatch; found : x.Test required: ?{val x: ?} object x { class Test { private[this] var x0: Int = 0 private[this] def x = x0 def x_=(a: Int) = x0 = a } val t = new Test t.x = 1 } Getter可见 object x { class Test { private[this] var x0: Int = 0 private[x] def x = x0 def x_=(a: Int) = x0 = a } val t = new Test t.x = 1 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |