Jonathan Hollingsworth
10/07/2021, 6:29 PMMyClass(**mutableMapObj)
I’ve tried various options using kclass and callBy, but what I really want to do is destructure the mutableMapObj into the class instantiation call.
I.e. my MyClass.pleaseTakeAMap(mutableMapObj)
is equivalent to MyClass(param1 = mutableMapObj["param1"], param2 = mutableMapObj["param2"]
Ideally I could do this without have to add to companion object onto each data class.Jonathan Hollingsworth
10/07/2021, 6:42 PMJonathan Hollingsworth
10/07/2021, 7:10 PMfun <T : Any> mapToObject(map: Map<String, Any?>, klass: KClass<T>) : T {
//Get default constructor
val constructor = klass.constructors.elementAt(1)
//Map constructor parameters to map values
val args = constructor
.parameters
.map { it to map.get(it.name) }
.toMap()
//return object from constructor call
return constructor.callBy(args)
}
That’s a relief!Veniamin Viflyantsev
10/07/2021, 7:10 PMimport kotlin.reflect.KClass
fun <T : Any> Map<String, Any>.convertTo(clazz: KClass<T>): T {
assert(clazz.isData)
val constructor = clazz.constructors.firstOrNull() ?: throw IllegalArgumentException("no constructor found")
return constructor.callBy(
constructor.parameters.associateWith { parameter ->
this[parameter.name]
}.filter { (parameter, value) ->
!parameter.isOptional || value != null
}
)
}
Jonathan Hollingsworth
10/07/2021, 7:13 PMclazz.constructors.first()
and I needed to access the second.
The first had additional parameters not in the data class primary constructor.Veniamin Viflyantsev
10/07/2021, 7:20 PMKClass::constructors
, it can be 1st, it can be 2nd, collection of constructors can be a Set
which doesn't imply any orderingJonathan Hollingsworth
10/07/2021, 8:00 PMVeniamin Viflyantsev
10/07/2021, 8:22 PMclazz.constructors.maxByOrNull { it.parameters.size }
Jonathan Hollingsworth
10/07/2021, 8:26 PMJonathan Hollingsworth
10/07/2021, 8:26 PMJonathan Hollingsworth
10/07/2021, 8:33 PMclazz
but in Python we tend to use klass
- is that Kotlin ‘standard’?Joffrey
10/08/2021, 12:09 AMclazz
used in both Java and Kotlin. AFAIR I came across klass
a couple times too, so you can also follow your heart here 🙂