StackOverflow with Custom Delegate

Hi, i’ve some trouble with custom delegates.

i simply want to create a custom delegate that checks if the value passed is greater than 0, and updates the value if the condition is respected.

how can i do it? thanks

class MyDelegate() : ReadWriteProperty<PositiveNumber, Int>
{
override fun getValue(thisRef: PositiveNumber, property: KProperty<*>): Int {
return thisRef.number
}

override fun setValue(thisRef: PositiveNumber, property: KProperty<*>, value: Int) {
if(value > 0) thisRef.number=value
}
}

class PositiveNumber()
{
var number : Int by MyDelegate()
}

The important thing to note when using a delegated property is that the class using the delegate (in your case PositiveNumber does not have a backing field for the property. Normally, it is the delegates responsibility to hold the value. The class using the delegate just delegates all reads and writes on that property to the delegate. In your case, that means that whenever the number property of a PositiveNumber is accessed, it calls one of the methods on the delegate. The delegate in turn tries to access the number property of the PositiveNumber. This results in infinite recursion.

For the case you present, I would not really consider a delegated property to be the right solution. In your case, I would just implement PositiveNumber.number as a normal non-delegated property with a custom setter. Alternatively it could be an inline class.

Are you considered built-in observable or vetoable?

thanks for your answers! they were in my spam emails, so i’ve just noticed :sweat_smile: :sweat:

in conclusion, a custom delegate can’t work as getter/setter for a property, because it would generate an infinite recursion.

thanks to all!