Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 05 / Topic 7 of 8

Basic overloading

Overloading is giving more than one function the same name, as long as their parameter lists differ -- in count, in type, or both. The compiler picks the right one by matching the arguments at the call site; nothing about overloading involves the return type.

fun greet(name: String): String = "Hello, $name!"

fun greet(name: String, timeOfDayGreeting: String): String = "$timeOfDayGreeting, $name!"

fun greet(customerId: Int): String = "Hello, customer #$customerId!"

fun main() {
    println(greet("Rohan"))
    println(greet("Rohan", "Good morning"))
    println(greet(5))
}
Hello, Rohan!
Good morning, Rohan!
Hello, customer #5!

Three functions, one name: greet(5) can only mean the Int overload, since 5 isn't a String, and greet("Rohan", "Good morning") can only mean the two-String overload. The compiler resolves every call like this at compile time, from the static types of the arguments -- the same resolution Part 1 showed kotlinc doing for everything else.

🔍 Going deeper: a default argument can make two overloads genuinely ambiguous, not just similar. fun bill(amount: Int): String alongside fun bill(amount: Int, taxPercent: Int = 0): String is actually fine -- calling bill(100) resolves to the first one, the exact match that needs no default filled in, verified by running it. True ambiguity needs two overloads that both require a default to be filled for the same call, with nothing to prefer between them:

fun f(a: Int, b: Int = 0): String = "int version: $a,$b"
fun f(a: Int, b: String = "x"): String = "string version: $a,$b"
f(5)   // ambiguous: both candidates need b's default, and neither wins
error: overload resolution ambiguity between candidates:
fun f(a: Int, b: Int = ...): String
fun f(a: Int, b: String = ...): String

The fix is the same either way: give the call enough arguments (or enough named ones) that only one candidate still fits.

Full program: examples/07_overloading.kt.

Done here? The practice set for Part 5 — including the solutions — is on the part page.

Search the guide