Set unique value

Hello, is here in Kotlin a unique setter like this?
setUnique(value) = if (key != value) key = value
If not, maybe it could be a nice alias.

I don’t understand what you’re asking.

Kotlin has setters on all properties.

Do you mean some kind of special setter that only runs if the current value isn’t already equal to the new value? Maybe someone with more JVM knowledge can clarify, but there’s a good chance a normal self assignment would be optimized away in many cases. Even if not, since all you’re doing is setting a reference, it’s probably more performant to just do the assignment instead of calling a setter, the getter twice, and doing a comparison.

If that’s what you’re asking for, what’s your use case? The first thing I can think of is that you might want it for performance reasons–which I suspect won’t change much or even be trivially worse when calling some kind of setUnique.

1 Like

I used it as a kind of a circular dependency protection. Maybe it’s not a good design but I saw this trick in a one of different language frameworks some years ago.

So in order to avoid a recursive setter?
Or maybe instead used to avoid some kind of recursive referencing that keep objects from being garbage collected?

I’m not trying to say I like or dislike the idea, I just haven’t yet understood the use case it solves.

Yes, to avoid the recursion and sometimes if data is complex to optimize performance (and maybe some future calculations like in observe methods)

Okay, so to avoid a recursive setter that would throw a StackOverflow–not a recursive loop of references that the garbage collector would have to deal with. :slight_smile:

The only thing is that a recursive setter that checks equality doesn’t protect us from that recursion.

The idea of setUnique is that it won’t attempt to set the value unless the value isn’t equal. This won’t stop a recursive setter from throwing a StackOverflow error. It might accidentally stop some StackOverflows by skipping some assignments, but there’s the cause of the recursion could be anywhere–not only due to setting a value to itself.

This kind of protection may be applicable in some specific use case. If it is, implementing it as a normal setter will fix the issue without requiring the caller to have to decipher when to use a general purpose setUnique.

There’s quite a few risks of recursion in any method call including setters because that call is expected to do something. Even setUnique risks recursion by calling .equals() and the property getters. There may be another use for this in a framework or language that can help clarify why it might be useful but it’s hard to see any benefit without some tangible examples of it being used.