dimanche 27 septembre 2020

Kotlin pass KType as generic parameter

I have a situation where I want to call a function to produce an object of a type for which I have just a KType description of.

Basically I have:

fun<T> coolFunction(from : String) : T = // Okay, I'll be honest - its a JSON parser
...
fun myOtherFunction(foo : KCallable<MyReturnType>) : MyReturnType {
    val args = mutableMapOf<KParameter, Any?>()
    ...
    for (parameter in foo.parameters) {
        ...
        val argValue = coolFunction<parameter.type>(someStringIhave)
        args[parameter.name] = argValue
    }
    ...
    return foo.callBy(args)
}

The issue is of course that the coolFunction<parameter.type>(someStringIhave) isn't correct syntax. I don't know how to get the right syntax though, I assume I'll have to use some more reflective API, but I can't seem to figure out how.





Aucun commentaire:

Enregistrer un commentaire