Once I have a class like bellow:
class Mutex {
var a: String? = null
set(a) {
this.b = null
field = a
}
var b: String? = null
set(b) {
this.a = null
field = b
}
}
While I call any of properties setter mutex.a = "A" or mutex.b = "B" will cause StackOverflowError, I knew that it's recusive invoke problem. How to avoid these language level syntax issue because It doesn't contains this.b.field = null sentence.
The StackOverflowError occurs because setting a automatically sets b to null, which in turn sets a to null again, creating an infinite recursion. To avoid this, you can introduce a private backing field to control when the setter should actually modify the other property, thus breaking the recursion.