samedi 24 octobre 2020

How can I get property reference from an class reference or generic type?

I'm trying to replace assign() method with a niceAssign():

    class Builder<T : Any>(val kClass: KClass<T>) {
        fun <K> assign(prop: KProperty1<T, K>, value: K): Builder<T> = TODO("doing other stuff here")
        fun <K> niceAssign(call: KClass<T>.() -> Pair<KProperty1<T, K>, K>) : Builder<T> {
            val (prop, value) = call(kClass)
            return assign(prop, value)
        }
    }

    val builder = Builder(Data::class)
    builder.assign(Data::someProperty, "some value") // (1)
    builder.niceAssign { ::someProperty to "some value" } // (2)

Since builder object is generified with Data class, I don't really need to explicitly indicate Data class while passing a property reference. Assign method already knows which class that property belongs to. So I don't want write "Data::" every time in assign method (like in code (1)), but I want to pass "Data::" as a receiver property for niceAssign param, so I could reference ::someProperty from "this" object.

This code snippet doesn't work because I'm passing KClass as a receiver, and KClass doesn't have property references of T. So, is there any way to make it work?





Aucun commentaire:

Enregistrer un commentaire