vendredi 29 octobre 2021

Call reflected constructor with default parameters in Kotlin

I'm restoring complex data from json files and some of them requires call for specific types that does not have empty constructors, but constructors with default parameters.

There is a method for creation an empty object,

abstract class Restorer {
        inline fun <reified T>load(ctx: T): T {
             var that: T = reset(ctx)
             // ...
        }

        inline fun <reified T>reset(ctx: T): T {
            val primaryConstructorT = T::class.constructors.find {
                it.parameters.isEmpty() || it.parameters.all { prm ->  prm.isOptional }
            }
            return primaryConstructorT!!.call() // <--- here is a problem
        }
}

So in some cases primaryConstructorT is a reflection for constructor with optional params, but direct call for that produces an exception. Callable expects 2 arguments, but 0 were provided.

There is the case for creation simple data class

data class DataClass (val foo: List<String> = listOf(), val bar: List<Int> = listOf())
// ...
var context: DataClass? = null;
// ...
context = Restorer.load(context)

Is there any method to call it





Aucun commentaire:

Enregistrer un commentaire