Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload resolution ambiguity... or not?

Here is some dull overloading:

class Dummy() {
    fun f(x: Unit) : String = "Disco"
    fun f(x: Unit, y: Unit = Unit) : String = "Mambo"
}

I'm not sure to understand why, but this works:

fun main(args: Array<String>) {
    println(Dummy().f(Unit))           // Echoes “Disco”
}

However, that does not:

fun main(args: Array<String>) {
    println((Dummy::f)(Dummy(), Unit)) // Fails: “Overload resolution ambiguity”
}

Any insight on the outcome difference?

like image 888
cuihtlauac Avatar asked Oct 30 '25 13:10

cuihtlauac


1 Answers

When you are calling Dummy::f there are two candidates with the same name f:

fun f(x: Unit) : String = "Disco"
fun f(x: Unit, y: Unit = Unit) : String = "Mambo"

The compiler does not know which one to take. This is because the function reference does not specify parameters, even if you change the signature of one of them to:

fun f(x: Int) : String = "Disco"
fun f(s: String) : String = "Mambo"

You will still have a problem because there is no way to infer the type with this statement: Dummy::f.

As a note, function references are used mostly to avoid lambda creations.


For example, if you have: (different names)

class Dummy() {
    fun f(x: Unit) : String = "Disco"
    fun g(x: Int) : String = "Mambo"
}

fun main(args: Array<String>) {
    val f = Dummy::f
    val g = Dummy::g
}

the type of f is KFunction2<Dummy, Unit, String> and gtype is KFunction2<Dummy, Int, String>

But if you define: (equal names)

class Dummy() {
    fun f(x: Unit) : String = "Disco"
    fun f(x: Int) : String = "Mambo"
}

fun main(args: Array<String>) {
    val f = Dummy::f
    val g = Dummy::f
}

You will have the “Overload resolution ambiguity” error because the compiler's information is too restricted to infer the correct function from the two with the same name.

The problem is not the number of arguments, but using a function reference with many candidates.

like image 191
crgarridos Avatar answered Nov 01 '25 05:11

crgarridos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!