jeudi 18 novembre 2021

Kotlin generic type extension with reflect

fun <T: Any, R> T.convertTo(r : KCallable<R>) : R {
    val that = this
    with(r) {
        val propertiesByName = that::class.memberProperties.associateBy { it.name }
        callBy(parameters.associate { parameter ->
            parameter to propertiesByName[parameter.name]?.get(that)
        })
    }
}

I want to write a generic converter function to convert an object to another, the code like as above. Compiling with error for this line parameter to propertiesByName[parameter.name]?.get(that)

Type mismatch.
Required: Nothing
Found: T

How to solve this problem?





Aucun commentaire:

Enregistrer un commentaire