@@ -28,45 +28,43 @@ class FastKFunction<T>(private val function: KFunction<T>, instance: Any?) {
28
28
29
29
// この関数には確実にアクセスするためアクセシビリティ書き換え
30
30
function.isAccessible = true
31
- // TODO: valueParametersの生成関連の効率化
32
- valueParameters = parameters.filter { it.kind == KParameter .Kind .VALUE }
33
31
34
32
val constructor = function.javaConstructor
35
33
36
34
if (constructor != null ) {
35
+ valueParameters = parameters
37
36
bucketGenerator = BucketGenerator (parameters, null )
38
37
fullInitializedFunction = { constructor .newInstance(* it) }
39
38
} else {
40
39
val method = function.javaMethod!!
41
40
42
- // TODO: 必要な場面でインスタンスがnullならthrow
43
41
@Suppress(" UNCHECKED_CAST" ) // methodはTを返せないため強制キャスト
44
42
when (parameters[0 ].kind) {
45
43
KParameter .Kind .EXTENSION_RECEIVER -> {
46
- // 対象が拡張関数なら、instanceはreceiver
44
+ // 対象が拡張関数ならinstanceはreceiver、指定が無ければエラー
45
+ instance ? : throw IllegalArgumentException (
46
+ " Function requires EXTENSION_RECEIVER instance, but is not present."
47
+ )
48
+
49
+ valueParameters = parameters.subList(1 , parameters.size)
47
50
bucketGenerator = BucketGenerator (parameters, instance)
48
51
fullInitializedFunction = { method.invoke(null , instance, * it) as T }
49
52
}
50
53
KParameter .Kind .INSTANCE -> {
51
- if (instance != null ) {
52
- // 対象がインスタンスを要求する関数なら、instanceはobject
53
- bucketGenerator = BucketGenerator (parameters, instance)
54
- fullInitializedFunction = { method.invoke(instance, * it) as T }
55
- } else {
56
- // パラメータ上でインスタンスが要求されているが、入力のinstanceがnullだった場合、methodから取得を試みる
57
- try {
58
- val instanceFromClass = method.declaringObject!!
59
-
60
- bucketGenerator = BucketGenerator (parameters, instanceFromClass)
61
- fullInitializedFunction = { method.invoke(instanceFromClass, * it) as T }
62
- } catch (e: Exception ) {
63
- throw IllegalArgumentException (
64
- " Function requires INSTANCE parameter, but is not present." , e
65
- )
66
- }
54
+ valueParameters = parameters.subList(1 , parameters.size)
55
+
56
+ // 対象がインスタンスを要求する関数ならinstanceはobject、与えられたインスタンスがnullでもobjectからの取得を試みる
57
+ val nonNullInstance = instance ? : try {
58
+ method.declaringObject!!
59
+ } catch (e: Exception ) {
60
+ throw IllegalArgumentException (" Function requires INSTANCE parameter, but is not present." , e)
67
61
}
62
+
63
+ bucketGenerator = BucketGenerator (parameters, nonNullInstance)
64
+ fullInitializedFunction = { method.invoke(nonNullInstance, * it) as T }
68
65
}
69
66
KParameter .Kind .VALUE -> {
67
+ valueParameters = parameters
70
68
bucketGenerator = BucketGenerator (parameters, null )
71
69
72
70
fullInitializedFunction = if (instance != null ) {
0 commit comments