Hello! Does anybody know how to declare get() &amp...
# announcements
y
Hello! Does anybody know how to declare get() & set() for delegated properties correctly ? I'v tried like this and it haven't worked out.
Copy code
operator fun getValue(thisRef: Any, property: KProperty<*>): Any = properties[property.name]
        ?: throw IllegalStateException("Property ${property.name} hasn't been initialized!")

operator fun setValue(thisRef: Any, property: KProperty<*>, value: Any) {
    properties[property.name] = value
    listeners[property.name]?.invoke(value.toString())
}
d
Your code has two problems: - since you declared
Any
as return type of
set
and
value
type of
get
you can use
SharedStats
only for properties of type
Any
- you try to declare delegate for property with no receiver, so your
set
and
get
should take
Nothing?
as
thisRef
, not
Any
(since top-level properties has no receiver at all) Correct declaration should look like this:
Copy code
class SharedStatsFixed {
    operator fun <T> getValue(thisRef: Nothing?, property: KProperty<*>): T = TODO()
    operator fun <T> setValue(thisRef: Nothing?, property: KProperty<*>, value: T) {
        TODO()
    }
}
For more details check reference: https://kotlinlang.org/docs/reference/delegated-properties.html#property-delegate-requirements for
y
@dmitriy.novozhilov thank you, it helped! does it mean I have no chance to avoid unchecked cast ? and library-implementation uses unchecked cast as well (map-properties) ?
d
Yes it is
❤️ 1