https://kotlinlang.org logo
#reflect
Title
# reflect
d

diesieben07

04/23/2018, 9:43 AM
Is there a way to go from a
KProperty1<T, R>
to a
KProperty0<R>
when I have the receiver object (
T
)? I.e., can I "bind" a receiver to a property?
u

udalov

04/23/2018, 11:04 AM
Unfortunately, no
d

Deactivated User

04/23/2018, 11:45 AM
A bit hacky, but maybe it works for you:
Copy code
class Demo(val a: Int)

fun <T, R> KProperty1<T, R>.bind(receiver: T): KProperty0<R> {
    return object : KProperty0<R>, KProperty<R> by this {
        override val getter: KProperty0.Getter<R> =
            object : KProperty0.Getter<R>, KProperty.Getter<R> by this@bind.getter,
                    () -> R by { this@bind.getter(receiver) } {
            }

        override fun get(): R = this@bind.get(receiver)
        override fun getDelegate(): Any? = this@bind.getDelegate(receiver)
        override fun invoke(): R = this@bind.invoke(receiver)
    }
}

object BindSample {
    @JvmStatic
    fun main(args: Array<String>) {
        val demo = Demo(10)
        val res = Demo::a.bind(demo)
        println(res.get())
    }
}
🙃 1
d

diesieben07

04/23/2018, 12:36 PM
Ouch 😄
But thank you.
5 Views