我们知道 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/