在Kotlin中对具有默认参数的函数使用callBy时出错 [英] Error when use callBy on a function with default parameters in Kotlin

查看:385
本文介绍了在Kotlin中对具有默认参数的函数使用callBy时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在Kotlin中调用没有默认参数值的函数.

I try to call a function with default parameters values without put parameters in 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<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)

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

Strange because the parameter is not required but optional...

推荐答案

通过一些测试,KClass不会跟踪其创建的实际对象,主要区别是this::class将使用this的运行时类型.

From a bit of testing, a KClass won't keep track of the actual object it was created from, the main difference being that this::class will use the runtime type of this.

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

You can verify this by querying information about all the parameters:

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

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

The first parameter is actually the instance of the class. Using this::callMeWithoutParams will keep track of this, removing the first row of the table, but naturally doesn't allow for finding the member by name. You can still call the method by providing the object:

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

这篇关于在Kotlin中对具有默认参数的函数使用callBy时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆