Function Reference to Overloaded functions

When a function is referenced like

val temp = Int::div

The compiler shows an error
“Overload resolution ambiguity:
public final operator fun div(other: Byte): Int defined in kotlin.Int
public final operator fun div(other: Double): Double defined in kotlin.Int
public final operator fun div(other: Float): Float defined in kotlin.Int
public final operator fun div(other: Int): Int defined in kotlin.Int
public final operator fun div(other: Long): Long defined in kotlin.Int
public final operator fun div(other: Short): Int defined in kotlin.Int”

How to solve this error?

Specify the type that you expect: val temp: Int.(Int) -> Int = Int::div

5 Likes

This does not work as well as expected for generics :

interface I {
    fun exists(n: Int): Boolean
    fun exists(n: String): Boolean
}

abstract class A<T> {
    abstract val m: I.(T) -> Boolean
}

class B : A<Int>() {
    override val m = I::exists // Overload resolution ambiguity
}

Specifying the type gets rid of the error:

class B : A<Int>() {
    override val m: I.(Int) -> Boolean = I::exists
}

I do agree though that the type here should be automatically inferred

How do I pass reference if the type is nullable?

For example

class CoolStuff {
    fun add(stuff: String) {
        println(stuff)
    }
    fun add(stuff: Int) {
        println(stuff)
    }
}

fun main() {
    val stuff: CoolStuff? = CoolStuff()

    val referenceToAdd: ((Int) -> Unit)? = stuff::add
}

Here the pic

Since stuff is nullable, it can’t be used directly in a bound callable reference. Instead, you can use stuff?.let { it::add }.