You are currently viewing Trying to get property reference from a type given by function receiver

Trying to get property reference from a type given by function receiver

I’m making a builder for any class. It’s based on KProperty reflections and it works well for now, but I want to improve an interface of it. Here is an example of current usage:

data class Data( val nonDef: String, val defValue: String = "DEF_VALUE", val copyValue: String = nonDef, val nonDef2: String, val aMap: Map<String, String> = emptyMap(),

) val builtData = Builder<Data>() .assign(Data::aMap, mapOf(“key” to “value”)) .assign(Data::nonDef2, “10”) .assign(Data::nonDef, “10”) .build()

I don’t like, that I have to specify Data:: receiver for every property reference in assign method. Data class is already given as generic for Builder, so I can pass only reference with receiving Data class.

So, I want to make new function prettyAssign() with callable argument, where class reference receiver is passed as function receiver for callable, so I could address ::aMap, ::nonDef and ::nonDef2 to implicit ‘this’. Here how it would look like:

class Builder&lt;T : Any&gt;(val kClass: KClass&lt;T&gt;) { fun &lt;K&gt; assign(prop: KProperty1&lt;T, K&gt;, value: K) : Builder&lt;T&gt; = TODO("doing all reflection magic here") fun &lt;K&gt; prettyAssign(call: KClass&lt;T&gt;.() -&gt; Pair&lt;KProperty1&lt;T, K&gt;, K&gt;) { val (prop, value) = call(kClass) return assign(prop, value) } } val builtData = DataBuilder&lt;Data&gt;() .prettyAssign { ::aMap to mapOf("key" to "value") } .prettyAssign { ::nonDef2 to "10" } .prettyAssign { ::nonDef to "10" } .build()

In that approach it doesn’t work, because KClass<T> doesn’t have references to T properties.

So, I don’t understand, is there a way to make prettyAssign() working

submitted by /u/stasmarkin
[link] [comments]