加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala:不能写setter没有getter?

发布时间:2020-12-16 09:48:19 所属栏目:安全 来源:网络整理
导读:这工作: 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 Butto
这工作:

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

我得到:错误:值计数不是ButtonCountObserver的成员

是否有可能创建一个setter(使用语法糖)没有getter?

解决方法

规范要求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 .

此外,为了使用设定器,吸气剂必须是可见的。我不知道如果这是指定

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
}

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
}

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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读