Home > Software engineering >  Call reflected constructor with default parameters in Kotlin
Call reflected constructor with default parameters in Kotlin

Time:10-30

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

CodePudding user response:

Maybe there is a better way, but you can use callBy() with an empty map:

return primaryConstructorT!!.callBy(emptyMap())

It automatically replaces missing parameters with their defaults.

  • Related