Scala:没有getter就不能写setter?

时间:2010-03-15 12:46:42

标签: scala

这有效:

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

是否可以在没有吸气剂的情况下创建一个具有语法糖的setter?

2 个答案:

答案 0 :(得分:29)

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

  

对作业的解释   一个简单的变量x = e取决于   x的定义。如果x表示a   可变变量,然后是赋值   将x的当前值更改为   评估结果   表达e的类型是   期望符合x的类型。   如果x是无参数函数   在某些模板中定义,并且相同   模板包含一个setter函数   x_ =作为成员,然后赋值x =   e被解释为调用   x _ =(e)该setter函数。   类似地,赋值f .x = e到   无参数函数x是   解释为调用f .x _ =(e   )。赋值f(args)= e with a   函数应用程序左侧   '='运算符被解释为f   .update(args,e),即调用   由f。

定义的更新函数

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

吸气剂不可见#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
}

答案 1 :(得分:0)

正如反语所指出的,必须有吸气剂存在。然而,作为一种解决方法(如果你不想提供一个吸气剂),你可以让getter返回Unit

object x {
  class Test { 
    private[this] var x0: Int = 0
    def x: Unit = ()
    def x_=(a: Int) = x0 = a 
  }
  val t = new Test
  t.x = 1
}

不要认为这被认为是好的风格(!),但它确实有效。

相关问题