https://kotlinlang.org logo
#getting-started
Title
# getting-started
h

holgerbrandl

03/25/2023, 5:24 PM
Hi there, why is `foo`` not marked as an overload resolution ambiguity error :
Copy code
fun <T> List<T>.foo(minSize: Int = 1, maxSize: Int = size, random: Random) = this
fun <T> List<T>.foo(proportion: Double = 1.0, random: Random) = this

fun main() {
    listOf("some", "thing").foo(random= Random(3))
}
Using kotlin 1.8.10
y

Youssef Shoaib [MOD]

03/25/2023, 5:32 PM
Functions with less arguments are considered higher priority
h

holgerbrandl

03/25/2023, 5:38 PM
That's imho a very odd convention. Is there a youtrack ticket for this?
y

Youssef Shoaib [MOD]

03/25/2023, 5:41 PM
It is intended behaviour afaik. It's useful to avoid resolution ambiguity for certain functions, like in your case, where one function is preferred over the other, unless the other function is the only one that can work (e.g. if you use
minSize=3
then the first function will be called). This behaviour is usually used by library devs through useless
unit1: Unit = Unit, unit2: Unit = Unit
parameters
The kotlin spec says, in the case of 2 functions being as valid as each other (as in, one function could forward itself to the other and vice versa):
• 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;
h

holgerbrandl

03/25/2023, 5:53 PM
Thanks for the clarification. In my case there is no preference, and both function calls would be legit, that's why I think its a confusing specification.
v

Vampire

03/25/2023, 7:39 PM
Why? One has 2 parameters with default value, one has 1 parameter with default value, so the second is more specific.
h

holgerbrandl

03/25/2023, 7:55 PM
Because to me, the number of default arguments does not correlate with specificity. I don't see how a user's intent to call one or the variant, would relate to the number of default arguments of either variant. If at all, I'd think this should be made opt-in e.g. via an annotation (smthg like @AllowAmbigousVariantByDefaultArgs)
4 Views