在 Kotlin 中对具有默认参数的函数使用 callBy 时出错

Error when use callBy on a function with default parameters in Kotlin

我尝试在 Kotlin 中使用默认参数值调用一个函数,而不使用 put 参数。

例如:

class Test {
    fun callMeWithoutParams(value : Double = 0.5) = value * 0.5

    fun callIt(name: String) = this.javaClass.kotlin
            .members.first { it.name == name }
            .callBy(emptyMap())
}

fun main(args: Array<String>) {
   println(Test().callIt("callMeWithoutParams"))
}

我有例外:

Exception in thread "main" java.lang.IllegalArgumentException: No argument provided for a required parameter: instance of fun 
 Test.callMeWithoutParams(kotlin.Double): kotlin.Double
     at kotlin.reflect.jvm.internal.KCallableImpl.callDefaultMethod(KCallableImpl.kt:139)
    at kotlin.reflect.jvm.internal.KCallableImpl.callBy(KCallableImpl.kt:111)
    at Test.callIt(Main.kt:15)
    at MainKt.main(Main.kt:20)

奇怪,因为参数不是必需的,而是可选的...

通过一些测试,KClass 不会跟踪创建它的实际对象,主要区别在于 this::class 将使用 [=14] 的运行时类型=].

您可以通过查询有关所有参数的信息来验证这一点:

 name | isOptional | index |     kind |          type
-----------------------------------------------------
 null        false       0   INSTANCE            Test
value         true       1      VALUE   kotlin.Double

第一个参数实际上是class的实例。使用 this::callMeWithoutParams 将跟踪 this,删除 table 的第一行,但自然不允许按名称查找成员。您仍然可以通过提供对象来调用该方法:

fun callIt(name: String) { 
    val member = this::class.members.first { it.name == name }
    member.callBy(mapOf(member.instanceParameter!! to this))
}