Kotlin setter infinite recursion

I am testing kotlin on Android and faced with a problem when the setters of two variables are called in infinite recursion because they try to change each other when they are initially 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 I will say that I use the following code:

 val example = Example() example.a = 10 

It ends up causing infinte recursions and, ultimately, stackoverflow. The installer for b calls the setter for a , which in turn again calls the installer for b . And it goes on forever.

I want to be able to update the value for b when a is set, and also to update the value a when b set.

Any thoughts from Kotlin experts there? Do I have to make Java as setters in this case so that my setter code is not called when I assign the value a or b . Or is there some great Kotlin kindness that I can use?

+5
source share
1 answer

In this example, you can calculate only one of the properties, for example

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

In general, however, Kotlin does not provide access to support fields for other properties. You will need to write it manually, for example.

 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 will not create its own support fields for these properties because they are never used.

+5
source

Source: https://habr.com/ru/post/1271043/


All Articles