本文介绍了覆盖 var 上的 setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个小小的问题,希望得到一个小小的答案:

A tiny question with hopefully a tiny answer:

我的类中有一个 var 需要在设置时触发某种更新.我知道 var 隐式地获取了两个方法,一个 getter 和一个 setter.是否有可能以某种方式覆盖 setter 方法以确保触发更新,而不会递归?我是说

I have a var in my class that needs to trigger some kind of update whenever it is set. I know that a var implicitly gets two methods with it, a getter and a setter. Is it possible to somehow override the setter method to make sure the update is triggered, without getting recursive? I mean

def a_=(x: Any) = { a = x; update }

应该是无限递归吧?

var 只在类外设置,在类内只读,也许有帮助.

The var is only set outside the class and read only inside the class, maybe that helps.

感谢收听.

推荐答案

你的代码永远不会是无限递归,因为它不会编译.由于编译器隐式创建了 Getter 和 Setter,因此您无法两次创建此类方法.我不知道编译器是否有理由不检查 Getter 或 Setter 是否存在,并且仅在没有这样的方法时才创建.

Your code will never be an infinite recursion because it won't compile. Due to implicit creation of a Getter and a Setter by the compiler you can't create such methods twice. I don't know if there is a reason why the compiler does not check if a Getter or a Setter exists and only if there are no such methods it create ones.

您可以通过重命名私有变量来避免此问题:

You can avoid this problem by renaming the private variable:

class X(private var _i: Int) {
  def i = _i
  def i_=(i: Int) {
    println(i)
    _i = i
  }
}

这些方法与编译器生成的方法具有相同的签名.

These methods have the same signature as the methods generated by the compiler.

如果 update 方法只被调用一次,您可以在伴随对象中执行此操作:

If the update method has only be called once you can do this inside the companion object:

object X {
  def apply(i: Int) = {
    update
    new X(i)
  }
}
class X(i: Int)

您是否有理由不喜欢不可变对象?如果没有,你可以复制旧的,同时设置一个新的值:

Is there a reason why you don't prefer an immutable object? If no, you can copy the old one and set a new value at the same time:

case class X(i: Int, j: Int)
val x1 = X(3, 6)
val x2 = x1.copy(i = 1) // x2 = X(1,6)

这篇关于覆盖 var 上的 setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:32