Scala的getter/setter问题

Dyl*_*lan 9 scala

我正在学习Scala,刚刚发现了创建自定义字段getter/setter的方法.我有一个简单的例子:

class Thing(private val a:Int){
  override def toString = "Thing[" + a + "]"
  private var _value = a
  def value = _value
  def value_= (newVal:Int) = _value = newVal
}
Run Code Online (Sandbox Code Playgroud)

在控制台上,我可以这样做:

scala> var t = new Thing(2)
t: dylan.code.Thing = Thing[2]

scala> t.value
res1: Int = 2

scala> t.value = 3

scala> t.value
res2: Int = 3
Run Code Online (Sandbox Code Playgroud)

现在我试图将这个概念带到一个稍微复杂的例子; 我会尝试将代码缩小到相关的内容:

abstract class CellExpression[Type] extends Publisher[CellUpdateEvent[Type]] with Subscriber[CellUpdateEvent[Type], CellExpression[Type]]{
    protected var cachedValue: Type = recalculateValue() 
    protected def recalculateValue(): Type

    protected def changeValue(newValue: Type):Unit = {
        val oldValue = value()
        if(newValue != oldValue){
            cachedValue = newValue
            publish(new CellUpdateEvent(this, oldValue, newValue))
        }
    }

    def value() = cachedValue
    def notify(pub: CellExpression[Type], event: CellUpdateEvent[Type]) = changeValue(recalculateValue())
}
//....
class CellVariable[Type](private val initialValue:Type) extends CellExpression[Type]{
    cachedValue = initialValue
    protected def recalculateValue() = { cachedValue }
    override def toString = "CellVariable[" + value + "]"
    def value_= (newValue:Type) = {changeValue(newValue)}
}
Run Code Online (Sandbox Code Playgroud)

据我所知,我已经做了我需要做的事情,以便能够value通过它的吸气剂和制定者作为一个领域进行治疗.但是当我在控制台中尝试时,我得到:

scala> var i = new CellVariable(2)
i: dylan.code.CellVariable[Int] = CellVariable[2]

scala> i.value = 3
<console>:11: error: reassignment to val
       i.value = 3
               ^
Run Code Online (Sandbox Code Playgroud)

我做错了什么,我该如何解决?

Dyl*_*lan 11

我实际上偶然发现了解决方案.

我声明我的值函数的行def value() = cachedValue是罪魁祸首.如果我删除括号以使该行def value = cachedValue看起来像我预期的那样工作.

  • 究竟.赋值表示法只有在定义了相应的无参数getter(没有`()`时,如你所说)的情况下才有效(尽管允许使用隐式参数).如果你只想提供一个没有getter的setter,我要做的是`def value(隐式ev:Nothing)= error("不应该被称为")`. (2认同)