Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala:can';没有getter就不能写setter?_Scala - Fatal编程技术网

Scala:can';没有getter就不能写setter?

Scala:can';没有getter就不能写setter?,scala,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 B

这项工作:

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
我得到:
错误:值计数不是ButtonContobserver的成员


是否可以在没有getter的情况下创建setter(使用语法糖)?

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

对转让的解释 简单变量x=e取决于 x的定义。如果x表示a 可变变量,然后是赋值 将x的当前值更改为 评价结果 表达式e。e的类型是 应符合x的类型。 如果x是无参数函数 在某些模板中定义,并且相同 模板包含一个setter函数 x_uu=作为成员,然后分配x= e被解释为调用 该setter函数的x=(e)。 类似地,将f.x=e赋值给 无参数函数x是 解释为调用f.x_ux=(e ).一个赋值f(args)=e和一个 函数应用程序位于 “=”运算符被解释为f .update(args,e),即调用 由f定义的更新函数的

此外,为了使用setter,getter必须可见。我不确定是否指定了此项

吸气剂不可见#1 吸气剂不可见#2
正如追溯词所指出的,必须有一位获得者在场。但是,作为一种解决方法(如果您不想提供getter),可以使getter返回
单元

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
}
不要认为这是一种好的风格(!),但它是有效的。

回复中的“Getter Visible”示例不起作用:14:错误:类型不匹配;找到:x.type(具有基础类型对象x)必需:?{val x:?}
//<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
}
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
}
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
}