LambdaBeta
LambdaBeta

Reputation: 1505

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:

inline fun<reified 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.

Upvotes: 1

Views: 697

Answers (1)

Mohsen
Mohsen

Reputation: 1389

you should change your coolFunction to get the parameter. it can't be done with a generic function. unfortunately, you didn't provide the code for your coolFunction and I can't help you with its implementation but if you want to do this you should pass the class instead of using generics. and if you call other generic functions in your cool function change them all. pass the parameter and deal with it in your cool function. you can't call it this way there is no way. you have to change the signature.

also, your args was wrong. the keys should be parameters, not their name. I corrected it.

fun coolFunction(from: String, param: KParameter) {} // Okay, I'll be honest - its a JSON parser

fun myOtherFunction(foo : KCallable<String>) : MyReturnType {
    val args = mutableMapOf<KParameter, Any?>()

    for (parameter in foo.parameters) {
        val argValue = coolFunction("someStringIhave", parameter)
        args[parameter] = argValue
    }

    return foo.callBy(args)
}

Upvotes: 1

Related Questions