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<T : Any>(val kClass: KClass<T>) { fun <K> assign(prop: KProperty1<T, K>, value: K) : Builder<T> = TODO("doing all reflection magic here") fun <K> prettyAssign(call: KClass<T>.() -> Pair<KProperty1<T, K>, K>) { val (prop, value) = call(kClass) return assign(prop, value) } } val builtData = DataBuilder<Data>() .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]