简体   繁体   English

kotlin setter无限递归

[英]kotlin setter infinite recursion

I am testing out kotlin on Android and ran into a problem where the setters of two variables get called in an infinite recursion because they try to change each other when they are originally set. 我正在测试Android上的kotlin并遇到一个问题,即两个变量的setter在无限递归中被调用,因为它们在最初设置时会尝试互相更改。

Here is a sample code 这是一个示例代码

class Example {
    var a: Int = 0
        set(value) {
            b = a+10
        }

    var b:Int = 0
        set(value) {
            a = b-10
        }
}

And say I then use the following code: 然后说我然后使用以下代码:

val example = Example()
example.a = 10

It ends up causing an infinte recursions and eventually a stackoverflow. 它最终导致infinte递归并最终导致stackoverflow。 The setter for b calls the setter for a which in turn calls the setter for b again. 对于二传手b调用制定者a又调用了二传手b一次。 And it goes on for ever. 它永远持续下去。

I want to be able to update the value for b whenever a is set, but also update the value of a whenever b is set. 我希望能够为更新值b只要a设置,而且更新的值a每当b设置。

Any thoughts from the Kotlin experts out there? 那里有Kotlin专家的想法吗? Would I need to make Java like setters in this case so that my setter code doesn't get called whenever I assign a value to a or b . 在这种情况下,我是否需要使Java像setter一样,以便每当我为ab赋值时都不会调用我的setter代码。 Or is there some nifty Kotlin goodness that I can use? 或者,我可以使用一些漂亮的Kotlin善良吗?

For this example, you could only compute one of the properties, eg 对于此示例,您只能计算其中一个属性,例如

var a: Int = 0

var b: Int
    get() = 10 - a
    set(value) { a = 10 - value }

In general, though, Kotlin doesn't provide access to the backing fields of other properties. 但是,一般而言,Kotlin不提供对其他属性的支持字段的访问。 You'll have to write it manually, eg 你必须手动编写,例如

private var _a: Int = 0
var a: Int
    get() = _a
    set(value) {
        _a = value
        _b = 10 - value
    }

private var _b: Int = 10
var b: Int
    get() = _b
    set(value) {
        _b = value
        _a = 10 - value
    }

Kotlin won't generate its own backing fields for these properties because they are never used. Kotlin不会为这些属性生成自己的支持字段,因为它们从未被使用过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM