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): Stringalongsidefun bill(amount: Int, taxPercent: Int = 0): Stringis actually fine -- callingbill(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 winserror: overload resolution ambiguity between candidates: fun f(a: Int, b: Int = ...): String fun f(a: Int, b: String = ...): StringThe 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.