Home > Back-end >  How does kotlin determine which func to invoke when func overloads?
How does kotlin determine which func to invoke when func overloads?

Time:11-07

We know that kotlin allows us to use default parameters, but how does it determine which func to invoke when overload happens? like this below, the result is that the first test is invoked rather than the second, but why?

fun test() {

}

fun test(a: Int = 1) {

}
fun main() {
    test()
}

CodePudding user response:

The Kotlin language specification sets out rules for overload resolution.

First it states 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.

Then, later, in explaining how the most specific function is determined, 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

So there you go. In your example the test() function without the default parameter will be chosen as it has a lesser number of non-specified default parameters, and is thus more specific.

  • Related