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

Brian Carbone

11/13/2019, 3:55 PM
get() = field.coerceAtLeast(0)
I don't know how to make a delegate to replace this
l

Luke

11/13/2019, 4:02 PM
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

Casey Brooks

11/13/2019, 4:03 PM
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

Brian Carbone

11/13/2019, 4:50 PM
oh thanks guys. do libraries which create objects via reflection (e.g. ktor with Content Negotiation) bypass the delegate setter?
c

Casey Brooks

11/13/2019, 4:55 PM
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

Brian Carbone

11/13/2019, 4:57 PM
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

Casey Brooks

11/13/2019, 5:00 PM
You might try asking over in #ktor
b

Brian Carbone

11/13/2019, 5:02 PM
true, thank you
2 Views