对Kotlin中的默认参数使用callBy时出错

我尝试调用带有默认参数值的函数,而不将参数放在Kotlin中。

例如:

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) { 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将使用这个的运行时types。

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

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

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

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

chris给出的答案是完全正确的。

您也可以考虑将API更改为直接接受函数引用 ,这会使this参数过时。 callBy调用看起来像你已经尝试然后:

 fun callIt(func: KFunction<*>): Any? { return func.callBy(emptyMap()) } 

电话:

 with(Test()) { println(callIt(this::callMeWithoutParams)) }