https://kotlinlang.org logo
#announcements
Title
# announcements
h

Hullaballoonatic

06/19/2019, 6:44 PM
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

streetsofboston

06/19/2019, 6:46 PM
I think you could write your own property delegate class for this.
h

Hullaballoonatic

06/19/2019, 6:47 PM
yeah, that was my immediate thought. wanted to make sure one didn't already exist
m

mathew murphy

06/19/2019, 6:48 PM
Should you not use an actual Lock and the
withLock
extension?
h

Hullaballoonatic

06/19/2019, 6:49 PM
i idid not know that existed
m

mathew murphy

06/19/2019, 6:50 PM
That way you're safe if you want to start using the code in a multithreaded context.
k

karelpeeters

06/19/2019, 8:28 PM
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

Hullaballoonatic

06/19/2019, 8:36 PM
the actual shared operation was a placeholder
i could have made that more obvious by passing it as a parameter or something
k

karelpeeters

06/19/2019, 8:37 PM
Are you sure it's impossible to refactor the way you store information in your case? This partial redudancy/dependency is really bad.
h

Hullaballoonatic

06/19/2019, 10:44 PM
In a way, however, I think it's more intuitive the way I wrote it 😮
k

karelpeeters

06/19/2019, 10:47 PM
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

Hullaballoonatic

06/19/2019, 10:47 PM
oh, right, yeah that'd work too in this case
k

karelpeeters

06/19/2019, 10:47 PM
And it's probably easier to generalize in a property delegate.
h

Hullaballoonatic

06/19/2019, 10:48 PM
yeah
5 Views