@@ -34,10 +34,7 @@ import java.lang.reflect.InvocationTargetException
3434import java.lang.reflect.Modifier
3535import java.lang.reflect.ParameterizedType
3636import java.lang.reflect.Type
37- import kotlin.reflect.KClass
38- import kotlin.reflect.KFunction
39- import kotlin.reflect.KType
40- import kotlin.reflect.defaultType
37+ import kotlin.reflect.*
4138import kotlin.reflect.jvm.isAccessible
4239import kotlin.reflect.jvm.javaType
4340import kotlin.reflect.jvm.jvmName
@@ -84,12 +81,12 @@ fun <T : Any> createInstance(kClass: KClass<T>): T {
8481 */
8582private fun <T : Any > KClass<T>.easiestConstructor (): KFunction <T > {
8683 return constructors
87- .sortedBy { it.parameters.size }
84+ .sortedBy { it.parameters.withoutOptionalParameters(). size }
8885 .withoutParametersOfType(this .defaultType)
8986 .withoutArrayParameters()
90- .firstOrNull() ? : constructors.sortedBy { it.parameters.size }
91- .withoutParametersOfType(this .defaultType)
92- .first()
87+ .firstOrNull() ? : constructors.sortedBy { it.parameters.withoutOptionalParameters(). size }
88+ .withoutParametersOfType(this .defaultType)
89+ .first()
9390}
9491
9592private fun <T > List<KFunction<T>>.withoutArrayParameters () = filter {
@@ -101,10 +98,12 @@ private fun <T> List<KFunction<T>>.withoutArrayParameters() = filter {
10198 * This is especially useful to avoid infinite loops where constructors
10299 * accepting a parameter of their own type, e.g. 'copy constructors'.
103100 */
104- private fun <T : Any > List<KFunction<T>>.withoutParametersOfType (type : KType ) = filter {
101+ private fun <T : Any > List<KFunction<T>>.withoutParametersOfType (type : KType ) = filter {
105102 it.parameters.filter { it.type == type }.isEmpty()
106103}
107104
105+ private fun List<KParameter>.withoutOptionalParameters () = filterNot { it.isOptional }
106+
108107@Suppress(" SENSELESS_COMPARISON" )
109108private fun KClass <* >.hasObjectInstance () = objectInstance != null
110109
@@ -166,7 +165,7 @@ private fun <T : Any> KClass<T>.toClassObject(): T {
166165private fun <T : Any > KFunction<T>.newInstance (): T {
167166 try {
168167 isAccessible = true
169- return callBy(parameters.associate {
168+ return callBy(parameters.withoutOptionalParameters(). associate {
170169 it to it.type.createNullableInstance<T >()
171170 })
172171 } catch (e: InvocationTargetException ) {
0 commit comments