Compiler choosing between functions with no parameters vs functions with default parameters

Hi folks, sorry if this is something that has been asked before. I was wondering how the complier chooses between a function with no parameters and a function with default parameters.

Given:

func hello() {
    print("hi")
}

and

func hello(string: String = "") {
    print(string)
}

How does the complier chose which function to use when calling hello(). Does the function with no parameters take precedence?

Thanks :slight_smile:

That's correct. The general principle is that the most specific overload should win, and a function that always takes 0 parameters is "more specific" than a function that sometimes takes 0 parameters.

We (compiler contributors) should really write down some concrete instances of this rule, and ideally would have the entire ranking system documented; it isn't right now because (I hate to say) there's a bunch of emergent complexity there that the people who work on the expression type checker want to simplify before recording it properly.

8 Likes

That makes sense! Thanks

Also as an aside its worth pointing out that this "specificity" is a global property. For a given expression, a solution is a self-consistent assignment of overload choices to each declaration reference in the expression. There might be several valid solutions for a single expression. The type checker picks a solution among the set of valid solutions by find a solution that ranks higher than all other solutions. When a highest-ranked solution does not exist, we diagnose an ambiguity error.

Solution ranking takes into account both information recorded during constraint solving (the "score") and actual properties of the solutions under comparison.

In particular, we don't look at each overload set in isolation to pick a most specific overload and take them together, because doing so could produce a solution that is not correct or not most specific under the rules of the language.

And Jordan is right that the rules need to be a) simplified b) carefully studied and c) written down. Not necessarily in that order :)

12 Likes
Terms of Service

Privacy Policy

Cookie Policy