@@ -34,10 +34,7 @@ import java.lang.reflect.InvocationTargetException
34
34
import java.lang.reflect.Modifier
35
35
import java.lang.reflect.ParameterizedType
36
36
import 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.*
41
38
import kotlin.reflect.jvm.isAccessible
42
39
import kotlin.reflect.jvm.javaType
43
40
import kotlin.reflect.jvm.jvmName
@@ -84,12 +81,12 @@ fun <T : Any> createInstance(kClass: KClass<T>): T {
84
81
*/
85
82
private fun <T : Any > KClass<T>.easiestConstructor (): KFunction <T > {
86
83
return constructors
87
- .sortedBy { it.parameters.size }
84
+ .sortedBy { it.parameters.withoutOptionalParameters(). size }
88
85
.withoutParametersOfType(this .defaultType)
89
86
.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()
93
90
}
94
91
95
92
private fun <T > List<KFunction<T>>.withoutArrayParameters () = filter {
@@ -101,10 +98,12 @@ private fun <T> List<KFunction<T>>.withoutArrayParameters() = filter {
101
98
* This is especially useful to avoid infinite loops where constructors
102
99
* accepting a parameter of their own type, e.g. 'copy constructors'.
103
100
*/
104
- private fun <T : Any > List<KFunction<T>>.withoutParametersOfType (type : KType ) = filter {
101
+ private fun <T : Any > List<KFunction<T>>.withoutParametersOfType (type : KType ) = filter {
105
102
it.parameters.filter { it.type == type }.isEmpty()
106
103
}
107
104
105
+ private fun List<KParameter>.withoutOptionalParameters () = filterNot { it.isOptional }
106
+
108
107
@Suppress(" SENSELESS_COMPARISON" )
109
108
private fun KClass <* >.hasObjectInstance () = objectInstance != null
110
109
@@ -166,7 +165,7 @@ private fun <T : Any> KClass<T>.toClassObject(): T {
166
165
private fun <T : Any > KFunction<T>.newInstance (): T {
167
166
try {
168
167
isAccessible = true
169
- return callBy(parameters.associate {
168
+ return callBy(parameters.withoutOptionalParameters(). associate {
170
169
it to it.type.createNullableInstance<T >()
171
170
})
172
171
} catch (e: InvocationTargetException ) {
0 commit comments