is there a more clever way to accomplish this? may...
# announcements
h
is there a more clever way to accomplish this? maybe a way to generalize the behavior (delegation or annotation?), or does such a generalization already exist? https://pl.kotl.in/Z2joV2hL3
Copy code
class MyClass(foo: Int, bar: Int) {
    private var fooLock = false
    var foo = foo
    	set(v) {
            fooLock = true
            
            if (!barLock) bar += (v - field)
            field = v
            
            fooLock = false
        }
    
    private var barLock = false
    var bar = bar
    	set(v) {
            barLock = true
            
            if (!fooLock) foo += (v - field)
            field = v
            
            barLock = false
        }
}
s
I think you could write your own property delegate class for this.
h
yeah, that was my immediate thought. wanted to make sure one didn't already exist
m
Should you not use an actual Lock and the
withLock
extension?
h
i idid not know that existed
m
That way you're safe if you want to start using the code in a multithreaded context.
k
I think you should refactor the way you store information, for example:
Copy code
class MyClass(var foo: Int, bar: Int) {
    val delta = bar - foo
    
    var bar: Int
    	get() = foo + delta
    	set(v) { foo = v - delta }
}
That's a drop-in replacement for your class.
(it took me a while to figure that out because the above code is completely unreadable, it's almost intentionally obfusticated)
h
the actual shared operation was a placeholder
i could have made that more obvious by passing it as a parameter or something
k
Are you sure it's impossible to refactor the way you store information in your case? This partial redudancy/dependency is really bad.
h
In a way, however, I think it's more intuitive the way I wrote it 😮
k
Well then your opinion is wrong 🙃 . Another alternative would be to check for equality before setting:
Copy code
class MyClass(foo: Int, bar: Int) {
    var foo = foo
        set(v) {
            if (field != v) {
            	field = v
                bar += (v - field)
            }
        }
    
    var bar = bar
        set(v) {
            if (field != v) {
                field = v
                foo += (v - field)
            }
        }
}
Still ugly and unreadable but it's not as bad.
h
oh, right, yeah that'd work too in this case
k
And it's probably easier to generalize in a property delegate.
h
yeah