kotlin - 当 func 重载时,kotlin 如何确定调用哪个 func?

标签 kotlin jvm

我们知道 kotlin 允许我们使用默认参数,但是当发生重载时它如何确定调用哪个函数呢?如下所示,结果是调用第一个 test 而不是第二个,但为什么呢?

fun test() {

}

fun test(a: Int = 1) {

}
fun main() {
    test()
}

最佳答案

Kotlin 语言规范规定了 overload resolution 的规则.

首先它指出the general rule:

The compiler should first pick a number of overload candidates, which form a set of possibly intended callables (overload candidate set, OCS), and then choose the most specific function to call based on the types of the function and the call arguments.

然后,稍后在解释如何确定最具体的函数时,it states :

For each candidate we count the number of default parameters not specified in the call (i.e., the number of parameters for which we use the default value). The candidate with the least number of non-specified default parameters is a more specific candidate

所以就这样吧。在您的示例中,将选择不带默认参数的 test() 函数,因为它具有较少数量的未指定默认参数,因此更加具体。

关于kotlin - 当 func 重载时,kotlin 如何确定调用哪个 func?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74333456/

相关文章:

android - 地理编码器地址中的类型不匹配

java - 当应用程序集群时在两个 JVM 之间共享数据

Javap 输出 : difference static {} and public {}

java - 如何用 Java 编写正确的微基准测试?

java - Tomcat:调整内存比例

java - JVM迁移到jdk1.8.0_74后挂了

正则表达式替换所有非数字但允许 '+' 前缀

arrays - 如何创建具有请求长度的数组?

android - 如何解决ViewModel RunTimeException

android - 我无法完成 Activity