android - kotlin setter infinte recursion -


i testing out kotlin on android , ran problem setters of 2 variables called in infinte recursion because try change each other when set.

here sample code

class example {     var a: int = 0         set(value) {             b = a+10         }      var b:int = 0         set(value) {             = b-10         } } 

and use following code:

val example = example() example.a = 10 

it ends causing infinte recursions , stackoverflow. setter b calls setter a in turn calls setter b again. , goes on ever.

i want able update value b whenever a set, update value of a whenever b set.

any thoughts kotlin experts out there? need make java setters in case setter code doesn't called whenever assign value a or b. or there nifty kotlin goodness can use?

for example, compute 1 of properties, e.g.

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

in general, though, kotlin doesn't provide access backing fields of other properties. you'll have write 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 own backing fields these properties because never used.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -