Scala:没有 getter 就不能写 setter 吗?
这有效:
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
得到: error: value count is not a member of ButtonCountObserver
是否可以创建一个没有 getter 的 setter(使用语法糖)?
This works:
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
But this doesn't
class ButtonCountObserver {
private var cnt = 0 // private field
def count_=(newCount: Int) = cnt = newCount // writer method
// ...
}
val b = new ButtonCountObserver
b.count = 0
I get: error: value count is not a member of ButtonCountObserver
Is it possible to create a setter (with the syntactic sugar) without a getter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该规范要求定义 setter 和 getter 以便能够使用语法糖来调用 setter:
此外,为了使用 setter,getter 必须可见。我不确定是否指定了这个
Getter notvisible #1
Getter notvisible #2
Gettervisible
The spec requires that both a setter and getter are defined to be able to use the syntactic sugar for calling the setter:
Furthermore, the getter must be visible in order to use the setter. I'm not sure if this is specified
Getter not visible #1
Getter not visible #2
Getter visible
正如 Retronym 所指出的,必须有吸气剂存在。然而,作为一种解决方法(如果您不想提供 getter),您可以使 getter 返回
Unit
不要认为这被认为是好的风格(!),但它确实有效。
As retronym pointed out, there must be a getter present. As a workaround however (if you don't want to provide a getter), you can make the getter return
Unit
Don't think that that is considered good style (!), but it works.