简体   繁体   中英

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.

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. The setter for b calls the setter for a which in turn calls the setter for b again. 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.

Any thoughts from the Kotlin experts out there? 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 . Or is there some nifty Kotlin goodness that I can use?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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