Get Delegate Property Name on Initialization

Hello,

when we use delegates, the setter and getter methods provide us with the name of the property that is get or set. Is it possible to get the name of the property during initialization as well?

Example

var gamma by Delegate(1.0f)

class Delegate(value: Float) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): Float{
        return "$thisRef, thank you for delegating '${property.name}' to me!"
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Float) {
        println("$value has been assigned to '${property.name}' in $thisRef.")
    }
}

I would like to know the name “gamma” of the property “gamma” in my Delegation class, without the need to get or set the value first.


The reasoning behind this is I want to use Kotlin DSL to write and bind code for another language. It would be very practical if the output code had the same variable names for debugging purposes.

You can use provideDelegate() operator / PropertyDelegateProvider:

var gamma by PropertyDelegateProvider<Any?, Delegate> { _, prop ->
    println(prop.name)
    Delegate(1.0f)
}
1 Like

Thank you, that was exactly what I was searching for. I solved it by declaring the provideDelegate() operator in the delegate itself, returning itself.

class Delegate(value: Float) {
    /// ... ////

    operator fun provideDelegate(basicSF: Any?, property: KProperty<*>): Delegate {
        setName(property.name)
        return this
    }
}

I think this is the most beautiful and simple solution, without the need for any extra classes or providers like in the examples. :slight_smile:

1 Like