Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin setter infinite recursion

Tags:

android

kotlin

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?

like image 365
Mantaseus Avatar asked Aug 21 '17 00:08

Mantaseus


1 Answers

For this example, you could only compute one of the properties, e.g.

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, e.g.

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.

like image 167
ephemient Avatar answered Nov 09 '22 20:11

ephemient