`get() = field.coerceAtLeast(0)` I don't know how ...
# announcements
b
get() = field.coerceAtLeast(0)
I don't know how to make a delegate to replace this
l
Something like this?
Copy code
class PositiveIntDelegate {
    private var value = 0

    operator fun getValue(thisRef: Any?, property: KProperty<*>) = value

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
        this.value = value.coerceAtLeast(0)
    }
}
c
A delegate is just a class that has `getValue`/`setValue` operators, such as a Map or a class implementing
ReadWriteProperty
. So you can just create a delegate class with your custom coercion logic, and use that as the
by
https://pl.kotl.in/JbGqyFAB7
Here’s the docs on creating custom delegates, which may help clear it up https://kotlinlang.org/docs/reference/delegated-properties.html#property-delegate-requirements
b
oh thanks guys. do libraries which create objects via reflection (e.g. ktor with Content Negotiation) bypass the delegate setter?
c
properties with delegates do not have “backing fields”, so you can’t actually use reflection to set the field value itself. If the library sets fields through their setters (not accessing the
Field
directly), then it should work fine, and it should go through your delegate
b
oh I see... it's strange because the value always returns zero when I use the delegate, but every object is made with ktor
using their content negotiation
c
You might try asking over in #ktor
b
true, thank you