0
0
KotlinDebug / FixBeginner · 4 min read

How to Fix Overload Resolution Ambiguity in Kotlin

Overload resolution ambiguity in Kotlin happens when the compiler finds multiple functions matching a call and can't decide which one to use. To fix it, you can provide explicit type arguments, cast parameters, or rename functions to make calls unambiguous.
🔍

Why This Happens

Overload resolution ambiguity occurs when Kotlin finds two or more functions that could match a call equally well. The compiler then cannot decide which function to use, causing an error.

This usually happens when functions have similar parameter types or default arguments that overlap.

kotlin
fun printValue(value: Int) {
    println("Int: $value")
}

fun printValue(value: Double) {
    println("Double: $value")
}

fun printValue(value: Number) {
    println("Number: $value")
}

fun main() {
    printValue(10) // Calls printValue(Int)
}
Output
Int: 10
🔧

The Fix

You can fix overload resolution ambiguity by making the call explicit. For example, cast the argument to the desired type or rename functions to avoid overlap.

This helps the compiler pick the correct function without confusion.

kotlin
fun printValue(value: Int) {
    println("Int: $value")
}

fun printValue(value: Double) {
    println("Double: $value")
}

fun printValue(value: Number) {
    println("Number: $value")
}

fun main() {
    printValue(10 as Int)      // Calls printValue(Int)
    printValue(10.0)           // Calls printValue(Double)
    printValue(10 as Number)   // Calls printValue(Number)
}
Output
Int: 10 Double: 10.0 Number: 10
🛡️

Prevention

To avoid overload resolution ambiguity:

  • Use distinct parameter types for overloaded functions.
  • Avoid overlapping default parameters that confuse the compiler.
  • Use explicit casts or named arguments when calling overloaded functions.
  • Consider renaming functions if their signatures are too similar.

Linting tools and IDE warnings can help spot ambiguous overloads early.

⚠️

Related Errors

Similar errors include:

  • Type mismatch: When the argument type does not match any function signature.
  • Unresolved reference: When the function name is not found due to incorrect imports or typos.
  • Conflicting overloads: When two functions have the same signature after type erasure (in generics).

Fixes usually involve adjusting types, imports, or function signatures.

Key Takeaways

Overload resolution ambiguity happens when multiple functions match a call equally well.
Fix ambiguity by casting arguments or renaming functions to clarify intent.
Avoid overlapping parameter types and default arguments in overloaded functions.
Use explicit types and named arguments to guide the compiler.
Linting and IDE warnings help catch ambiguous overloads early.