Access members of custom delegates


#1

Hi,

I would like to access a function defined on my delegate:

class Delegate : ReadOnlyProperty<Any, Int> {

    override fun getValue(thisRef: Any, property: KProperty<*>): Int {
        return 12
    }

    fun f() {}
}

class Provider {
    operator fun provideDelegate(thisRef: Any, prop: KProperty<*>): Delegate {
        prop.isAccessible = true
        return Delegate()
    }
}

class MyClass {
    val x by Provider()
}

fun main() {
    val c = MyClass()
    val d = c::x.getDelegate()
}

The problem is that getDelegate() throws this:

kotlin.reflect.full.IllegalPropertyDelegateAccessException: Cannot obtain the delegate of a non-accessible property. Use "isAccessible = true" to make the property accessible

Not sure what else I can do to make the delegate “accessible”.

On a broader topic, I would love to be able to call c::x.f() as simply as this. Any way this could be done (or any plans to make it happen)?

Thank you.


#3

after looking more at your code, I think you don’t understand why your prop.isAccessible = true is not working. I think the isAccessible = true is applied only before setting a delegate, so that delegate has not been set to accessible…

What you need is to setAccessible after setting delegate… which I not supported in kotlin (delegateProvider only allow to handle delegate creation, not “wiring”)

I still believe you maybe are doing something wrong & there should be another way.

Maybe an extension could help you


#4

I don’t really now why your solution is not working but take a look at this workaround:


#5

Thanks, your answer on stackoverflow worked for my case.

I could have spent hours on this without this!


#6

Not my solution. Thats just the first thing I found on google :stuck_out_tongue_winking_eye:


#7

Damnit :slight_smile: