https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

RE

09/22/2023, 7:33 AM
Is it possible to directly obtain the delegate object in property delegation? Currently, I am using two properties because I can't directly get the delegate object. For example:
Copy code
private var _x = dirtyValue(x)
var x by _x
Copy code
fun <T> dirtyValue(value: T?, dirtyInit: Boolean = false) = DirtyDelegation(value, dirtyInit)

class DirtyDelegation<T> internal constructor(
    var value: T?,
    var dirty: Boolean
) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
        return value
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
        this.value = value
        this.dirty = true
    }
}
This is what I do now, I have to use 2 properties because I can't get the delegate object I want to access the dirty state, but
var x by dirtyValue
cannot do it
j

Joffrey

09/22/2023, 7:36 AM
I think you could use the KProperty and getDelegate: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-property1/get-delegate.html) But honestly this looks pretty clear to me with the 2 props, I don't think you would gain from using that reflection trick
r

RE

09/22/2023, 7:38 AM
🫠 OK, thanks