gpt4 book ai didi

Scala:没有getter就不能写setter?

转载 作者:行者123 更新时间:2023-12-03 10:27:39 25 4
gpt4 key购买 nike

这有效:

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(使用语法糖)?

最佳答案

该规范要求 setter 和 getter 都被定义为能够使用语法糖来调用 setter:

The interpretation of an assignment to a simple variable x = e depends on the definition of x. If x denotes a mutable variable, then the assignment changes the current value of x to be the result of evaluating the expression e. The type of e is expected to conform to the type of x. If x is a parameterless function defined in some template, and the same template contains a setter function x_= as member, then the assignment x = e is interpreted as the invocation x_=(e ) of that setter function. Analogously, an assignment f .x = e to a parameterless function x is interpreted as the invocation f .x_=(e ). An assignment f (args) = e with a function application to the left of the ‘=’ operator is interpreted as f .update(args, e ), i.e. the invocation of an update function defined by f .



此外,为了使用 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
}

setter/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
}

setter/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
}

关于Scala:没有getter就不能写setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2447132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com