Overloading
suggest changeOverloading means declaring several functions (or constructors) with the same name but different parameter lists. At each call site the compiler looks at the arguments and picks one of them.
Kotlin supports overloading of:
- top-level functions, member functions and extension functions
- constructors (primary + secondary)
- operators like
+,[]or(), which are just functions with special names; see Operator functions for those
Unlike Java, Kotlin has default and named arguments, so many overloads you would write in Java aren't needed. This article covers how the compiler picks an overload, when to use default arguments instead, and how @JvmOverloads creates overloads for Java callers.
Basic overloading
Overloads have to differ in the number or the types of their parameters:
fun area(side: Double): Double = side * side
fun area(width: Double, height: Double): Double = width * height
fun area(radius: Int): Double = Math.PI * radius * radius
fun main() {
println(area(3.0))
println(area(2.0, 5.0))
println(area(1))
}
9.0
10.0
3.141592653589793
Calling area(1) picks the Int overload. Overloading by type like this is legal, but it's easy to misread: area(1) and area(1.0) compute different shapes. Usually a different name (squareArea, circleArea) is the better choice.
The return type is not part of the signature. Two functions that differ only in what they return are a compile error:
fun parse(s: String): Int = s.toInt()
fun parse(s: String): Double = s.toDouble()
a2.kt:1:1: error: conflicting overloads:
fun parse(s: String): Double
fun parse(s: String): Int = s.toInt()
^^^^^^^^^^^^^^^^^^^^^^^^^
Use different names (parseInt, parseDouble) or a generic function with a type parameter.
How the compiler picks an overload
Overload resolution happens at compile time, in roughly these steps:
- Collect the functions with the given name that are visible from the call site, grouped by priority. For a call with an explicit receiver (
p.print(x)), members of the receiver come first, then extensions. For a call without a receiver, local functions come first, then members ofthis, then top-level and imported functions, and finally default imports such askotlin.*. - Starting from the highest-priority group, keep only the candidates that are applicable: the arguments can be passed to them, considering names, defaults and
vararg. - If one group has applicable candidates, pick the most specific one from that group. Lower-priority groups aren't looked at.
- If no single candidate is more specific than all the others, the call is ambiguous and won't compile.
"More specific" means its parameter types are subtypes of the other candidate's parameter types: Int is more specific than Number, and Number is more specific than Any.
The most specific type wins
fun show(x: Int) = "Int"
fun show(x: Long) = "Long"
fun show(x: Number) = "Number"
fun show(x: Any) = "Any"
fun main() {
println(show(1))
println(show(1L))
println(show(1.5))
println(show(1.toByte()))
println(show("text"))
val n: Number = 7
println(show(n))
}
Int
Long
Number
Number
Any
Number
Some things to notice:
1.5is aDouble. There's noDoubleoverload, so the closest supertype,Number, is used.Byteisn't converted toIntorLong. Kotlin has no implicit numeric widening, soshow(Number)is called.val n: Number = 7callsshow(Number)even though the value is anIntat runtime. Only the static (declared) type counts.
The missing widening can be surprising if you come from Java. With only Int, Long and Double overloads, passing a Byte variable doesn't compile at all:
fun process(x: Int) = "Int"
fun process(x: Long) = "Long"
fun process(x: Double) = "Double"
fun main() {
val b: Byte = 1
println(process(b))
}
e4.kt:7:13: error: none of the following candidates is applicable:
fun process(x: Int): String:
Argument type mismatch: actual type is 'Byte', but 'Int' was expected.
fun process(x: Long): String:
Argument type mismatch: actual type is 'Byte', but 'Long' was expected.
fun process(x: Double): String:
Argument type mismatch: actual type is 'Byte', but 'Double' was expected.
println(process(b))
^^^^^^^
Integer literals are the exception. A literal like 1 has no fixed type until it is used, so it can become a Long:
fun process(x: Long) = "Long"
fun process(x: Double) = "Double"
fun main() {
println(process(1))
println(process(3_000_000_000))
}
Long
Long
An integer literal never becomes a Double, though. You have to write 1.0.
Static types, not runtime types
Overloads are chosen from the declared types of the arguments, never from the runtime types. (Overriding is the opposite: it dispatches on the runtime type of the receiver. Polymorphism compares the two.) Smart casts do change the static type, so a check with is can switch which overload is called:
fun handle(value: Any) = "Any"
fun handle(value: String) = "String: ${value.uppercase()}"
fun main() {
val x: Any = "kotlin"
println(handle(x))
if (x is String) {
println(handle(x)) // x is smart-cast to String here
}
}
Any
String: KOTLIN
Ambiguous calls
If neither candidate is more specific than the other, the call is an error. Here each function is more specific in a different parameter:
fun f(a: Int, b: Any) = "Int, Any"
fun f(a: Any, b: Int) = "Any, Int"
fun main() {
println(f(1, 2))
}
a4.kt:5:13: error: overload resolution ambiguity between candidates:
fun f(a: Int, b: Any): String
fun f(a: Any, b: Int): String
println(f(1, 2))
^
To fix it, upcast an argument so that only one overload fits:
fun f(a: Int, b: Any) = "Int, Any"
fun f(a: Any, b: Int) = "Any, Int"
fun main() {
println(f(1, 2 as Any))
println(f(1 as Any, 2))
}
Int, Any
Any, Int
A better fix is to not declare overloads like these at all.
Nulls and nullable parameters
A bare null fits any nullable parameter. With two unrelated nullable types the call is ambiguous:
fun printIt(s: String?) = println("String: $s")
fun printIt(s: StringBuilder?) = println("StringBuilder: $s")
fun main() {
printIt(null)
}
a8.kt:5:5: error: overload resolution ambiguity between candidates:
fun printIt(s: String?): Unit
fun printIt(s: StringBuilder?): Unit
printIt(null)
^^^^^^^
Give the null a type to pick one:
fun printIt(s: String?) = println("String: $s")
fun printIt(s: StringBuilder?) = println("StringBuilder: $s")
fun main() {
printIt(null as String?)
val sb: StringBuilder? = null
printIt(sb)
}
String: null
StringBuilder: null
Here a nullable overload is chosen for a non-null argument:
fun label(x: String) = "String"
fun label(x: Int?) = "Int?"
fun label(x: Long?) = "Long?"
fun main() {
println(label("a"))
println(label(1))
val maybe: Int? = null
println(label(maybe))
}
String
Int?
Int?
You can't overload on nullability alone, for example greet(name: String) and greet(name: String?). Both compile to the same JVM method:
a3b.kt:1:1: error: platform declaration clash: The following declarations have the same JVM signature (greet(Ljava/lang/String;)Ljava/lang/String;):
fun greet(name: String): String defined in root package
fun greet(name: String?): String defined in root package
vararg is the least specific
A function with a fixed parameter wins over a vararg function when both fit:
fun log(message: String) = println("one: $message")
fun log(vararg messages: String) = println("vararg: ${messages.joinToString()}")
fun main() {
log("a")
log("a", "b")
log()
}
one: a
vararg: a, b
vararg:
The standard library uses this pattern for speed: listOf(element) and listOf(vararg elements) are separate overloads, so a one-element list doesn't need an array. See Vararg Parameters in Functions for more on vararg.
Concrete types win over generics
A non-generic overload is more specific than a generic one:
fun <T> describe(value: T) = "generic T"
fun describe(value: String) = "String"
fun describe(value: CharSequence) = "CharSequence"
fun main() {
println(describe("hi"))
println(describe(StringBuilder("hi")))
println(describe(42))
}
String
CharSequence
generic T
Members win over extensions
If a member function is applicable, it is called, even when an extension has a more specific parameter type. The compiler even warns that the extension is shadowed:
class Printer {
fun print(x: Any) = "member print(Any)"
}
fun Printer.print(x: String) = "extension print(String)"
fun Printer.print(x: Any) = "extension print(Any)"
fun main() {
val p = Printer()
println(p.print(42))
println(p.print("hi"))
}
b4.kt:5:13: warning: this extension is shadowed by a member: 'fun print(x: Any): String' defined in 'Printer'.
fun Printer.print(x: String) = "extension print(String)"
^^^^^
b4.kt:6:13: warning: this extension is shadowed by a member: 'fun print(x: Any): String' defined in 'Printer'.
fun Printer.print(x: Any) = "extension print(Any)"
^^^^^
member print(Any)
member print(Any)
p.print("hi") calls the member print(Any) and never reaches print(String), because members are a higher-priority group. You can add a member with a new signature to a class, but you can't use an extension to replace the behavior of an existing member. See Potential Pitfall Extensions are Resolved Statically for more.
Closer scopes win
Local functions are looked at before top-level ones, even when the top-level one is more specific:
fun format(x: Int) = "top-level format($x)"
fun main() {
fun format(x: Any) = "local format($x)"
println(format(1))
}
local format(1)
For the same reason, your own top-level functions hide the ones from default imports. A top-level fun run(...) in your package takes priority over kotlin.run.
Overloading with lambdas
When overloads take function types with different numbers of parameters, the compiler uses the lambda's parameter list to choose:
fun execute(block: () -> Unit) { println("() -> Unit"); block() }
fun execute(block: (Int) -> Unit) { println("(Int) -> Unit"); block(7) }
fun execute(block: (Int, Int) -> Unit) { println("(Int, Int) -> Unit"); block(1, 2) }
fun main() {
execute { -> println(" no parameters") }
execute { n -> println(" got $n") }
execute { a, b -> println(" got $a and $b") }
}
() -> Unit
no parameters
(Int) -> Unit
got 7
(Int, Int) -> Unit
got 1 and 2
Note the explicit -> in the first call. A lambda without declared parameters, { ... }, can be either () -> Unit or (Int) -> Unit with an implicit it, so it's ambiguous:
fun execute(block: () -> Unit) { println("() -> Unit"); block() }
fun execute(block: (Int) -> Unit) { println("(Int) -> Unit"); block(7) }
fun main() {
execute { println("which one?") }
}
c1b.kt:5:5: error: overload resolution ambiguity between candidates:
fun execute(block: () -> Unit): Unit
fun execute(block: (Int) -> Unit): Unit
execute { println("which one?") }
^^^^^^^
If the overloads differ only in the lambda's return type, the compiler normally can't pick, because it resolves the call before it analyzes the lambda body. The @OverloadResolutionByLambdaReturnType annotation turns that on. It's how the standard library offers sumOf { } for Int, Long, Double and others:
@OptIn(kotlin.experimental.ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
@JvmName("computeInt")
fun compute(f: () -> Int) = "Int result: ${f()}"
@JvmName("computeString")
fun compute(f: () -> String) = "String result: ${f()}"
fun main() {
println(compute { 40 + 2 })
println(compute { "forty-two" })
val words = listOf("a", "bb", "ccc")
println(words.sumOf { it.length }) // sumOf(selector: (T) -> Int)
println(words.sumOf { it.length * 0.5 }) // sumOf(selector: (T) -> Double)
}
Int result: 42
String result: forty-two
6
3.0
The @JvmName annotations are needed because of type erasure, explained next.
JVM signature clashes and @JvmName
On the JVM, generic type arguments are erased. List<Int> and List<String> are both java.util.List in bytecode, so these two overloads are valid Kotlin but can't both exist in a class file:
fun describe(items: List<Int>) = "ints: $items"
fun describe(items: List<String>) = "strings: $items"
c4.kt:1:1: error: platform declaration clash: The following declarations have the same JVM signature (describe(Ljava/util/List;)Ljava/lang/String;):
fun describe(items: List<Int>): String defined in root package
fun describe(items: List<String>): String defined in root package
Give them different JVM names with @JvmName. Kotlin callers still use the shared name and the overload is chosen from the type argument:
@JvmName("totalInts")
fun total(items: List<Int>): Int = items.sum()
@JvmName("totalDoubles")
fun total(items: List<Double>): Double = items.sum()
fun main() {
println(total(listOf(1, 2, 3)))
println(total(listOf(1.5, 2.5)))
}
6
4.0
The same thing happens with function types (() -> Int and () -> String are both Function0) and with T vs T?.
Default arguments vs overloads
In Java, a method with optional parameters is usually written as a chain of overloads that call each other. In Kotlin you write a single function with default values (see Named and optional parameters):
// Java style: 3 functions
fun connect(host: String) = connect(host, 80)
fun connect(host: String, port: Int) = connect(host, port, false)
fun connect(host: String, port: Int, secure: Boolean) = "connect($host, $port, $secure)"
// Kotlin style: 1 function
fun connect(host: String, port: Int = 80, secure: Boolean = false) = "connect($host, $port, $secure)"
The single function is better:
- the defaults are in one place instead of being spread across a chain of calls
- callers can skip any parameter by name, e.g.
connect("x", secure = true), which the Java-style chain can't do without another overload - there's less code to test and document
Use real overloads when the parameters have different types or meanings, not when some are just optional. A good example is a constructor that accepts a date as a LocalDate, a String or as year/month/day:
import java.time.LocalDate
class Event(val title: String, val date: LocalDate) {
// secondary constructors: different parameter types, not just fewer parameters
constructor(title: String, isoDate: String) : this(title, LocalDate.parse(isoDate))
constructor(title: String, year: Int, month: Int, day: Int) :
this(title, LocalDate.of(year, month, day))
override fun toString() = "$title on $date"
}
fun main() {
println(Event("Launch", LocalDate.of(2026, 1, 15)))
println(Event("Review", "2026-02-01"))
println(Event("Retro", 2026, 3, 9))
}
Launch on 2026-01-15
Review on 2026-02-01
Retro on 2026-03-09
More on secondary constructors in Constructors and init blocks.
Mixing defaults and overloads
If you have both, a candidate that doesn't need any default values is more specific than one that does:
fun connect(host: String) = "connect($host) - exact"
fun connect(host: String, port: Int = 80, secure: Boolean = false) =
"connect($host, $port, $secure) - with defaults"
fun main() {
println(connect("example.com"))
println(connect("example.com", 443))
println(connect("example.com", secure = true))
}
connect(example.com) - exact
connect(example.com, 443, false) - with defaults
connect(example.com, 80, true) - with defaults
This compiles, but it's confusing: connect("example.com") doesn't use the defaults from the second function. If two candidates both need defaults, the call is ambiguous:
fun send(to: String, retries: Int = 3) = "send A"
fun send(to: String, timeoutMs: Long = 1000) = "send B"
fun main() {
println(send("bob", 5))
println(send("bob", 5L))
println(send("bob"))
}
b2.kt:7:13: error: overload resolution ambiguity between candidates:
fun send(to: String, retries: Int = ...): String
fun send(to: String, timeoutMs: Long = ...): String
println(send("bob"))
^^^^
Notice that the error is reported only for send("bob"). The first two calls are fine, so the problem only shows up when someone writes that call. Don't mix defaults and overloads in ways that make a short call match more than one function.
Named arguments take part in resolution
Parameter names are checked too, so named arguments can make a call clearer and pick one overload:
fun resize(width: Int, height: Int) = "resize(width=$width, height=$height)"
fun resize(scale: Double) = "resize(scale=$scale)"
fun move(dx: Int, dy: Int = 0) = "move by ($dx, $dy)"
fun move(to: Pair<Int, Int>) = "move to $to"
fun main() {
println(resize(height = 200, width = 100))
println(resize(scale = 1.5))
println(move(dy = 5, dx = 1))
println(move(to = 3 to 4))
}
resize(width=100, height=200)
resize(scale=1.5)
move by (1, 5)
move to (3, 4)
Because callers can use parameter names, renaming a parameter is a source-breaking change in Kotlin, just like changing its type.
Overloading vs overriding in subclasses
A subclass can override a function and also add new overloads with the same name. An override inherits the default values of the base function and isn't allowed to declare its own:
open class Greeter {
open fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"
}
class LoudGreeter : Greeter() {
// the default value is inherited; an override can't declare its own
override fun greet(name: String, greeting: String) = "${greeting.uppercase()}, ${name.uppercase()}!"
// a new overload, not an override
fun greet(names: List<String>) = names.joinToString(" ") { greet(it) }
}
fun main() {
val g: Greeter = LoudGreeter()
println(g.greet("ann"))
println(LoudGreeter().greet(listOf("bob", "cid")))
}
HELLO, ANN!
HELLO, BOB! HELLO, CID!
Trying to change the default in the override:
d4.kt:6:57: error: an overriding function is not allowed to specify default values for its parameters.
override fun greet(name: String, greeting: String = "HEY") = "$greeting, $name!"
^^^^^
This rule exists because defaults are filled in at the call site from the static type. If an override could change them, g.greet("ann") and (g as LoudGreeter).greet("ann") could get different defaults.
@JvmOverloads: overloads for Java callers
Java has no default arguments. A Kotlin function with defaults compiles to one JVM method with every parameter, plus a synthetic $default helper that Java can't really use. So by default a Java caller has to pass every argument.
@JvmOverloads tells the compiler to also generate one overload for each trailing parameter with a default value:
@file:JvmName("Shapes")
fun makeRect(width: Int, height: Int = width, color: String = "black") =
"Rect(${width}x$height, $color)"
@JvmOverloads
fun makeCircle(radius: Int, color: String = "black", filled: Boolean = false) =
"Circle(r=$radius, $color, filled=$filled)"
class Label @JvmOverloads constructor(
val text: String,
val size: Int = 12,
val bold: Boolean = false,
) {
override fun toString() = "Label($text, $size, bold=$bold)"
}
javap shows what's in the class files:
Compiled from "Shapes.kt"
public final class Shapes {
public static final java.lang.String makeRect(int, int, java.lang.String);
public static java.lang.String makeRect$default(int, int, java.lang.String, int, java.lang.Object);
public static final java.lang.String makeCircle(int, java.lang.String, boolean);
public static java.lang.String makeCircle$default(int, java.lang.String, boolean, int, java.lang.Object);
public static final java.lang.String makeCircle(int, java.lang.String);
public static final java.lang.String makeCircle(int);
}
Compiled from "Shapes.kt"
public final class Label {
public Label(java.lang.String, int, boolean);
public Label(java.lang.String, int, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker);
public final java.lang.String getText();
public final int getSize();
public final boolean getBold();
public java.lang.String toString();
public Label(java.lang.String, int);
public Label(java.lang.String);
}
Calling them from Java:
public class Main {
public static void main(String[] args) {
// no @JvmOverloads: Java must pass every argument
System.out.println(Shapes.makeRect(10, 20, "red"));
// @JvmOverloads: Java gets one overload per trailing default
System.out.println(Shapes.makeCircle(5));
System.out.println(Shapes.makeCircle(5, "blue"));
System.out.println(Shapes.makeCircle(5, "blue", true));
System.out.println(new Label("Hi"));
System.out.println(new Label("Hi", 18));
System.out.println(new Label("Hi", 18, true));
}
}
Rect(10x20, red)
Circle(r=5, black, filled=false)
Circle(r=5, blue, filled=false)
Circle(r=5, blue, filled=true)
Label(Hi, 12, bold=false)
Label(Hi, 18, bold=false)
Label(Hi, 18, bold=true)
Calling Shapes.makeRect(10) from Java fails, because there's no such overload:
Bad.java:3: error: method makeRect in class Shapes cannot be applied to given types;
System.out.println(Shapes.makeRect(10));
^
required: int,int,String
found: int
reason: actual and formal argument lists differ in length
How the overloads are generated
The generated overloads drop parameters with defaults starting from the last one. Java callers can't skip a parameter in the middle, so there are only N+1 overloads for N defaults, not every combination. When a default parameter comes before a required one, it's dropped last:
@file:JvmName("D1")
@JvmOverloads
fun query(limit: Int = 10, table: String, desc: Boolean = false) = "$table $limit $desc"
public final class D1 {
public static final java.lang.String query(int, java.lang.String, boolean);
public static java.lang.String query$default(int, java.lang.String, boolean, int, java.lang.Object);
public static final java.lang.String query(int, java.lang.String);
public static final java.lang.String query(java.lang.String);
}
Restrictions and pitfalls
@JvmOverloads can't be used on abstract functions, including interface methods:
d2.kt:2:5: error: '@JvmOverloads' annotation cannot be used on interface methods.
d2b.kt:2:5: error: '@JvmOverloads' annotation cannot be used on abstract methods.
The generated methods also count as overloads, so they can clash with functions you wrote yourself:
fun tag(name: String) = "<$name>"
@JvmOverloads
fun tag(name: String, id: String = "") = "<$name id=\"$id\">"
e1.kt:1:1: error: platform declaration clash: The following declarations have the same JVM signature (tag(Ljava/lang/String;)Ljava/lang/String;):
fun tag(name: String): String defined in root package
fun tag(name: String): String defined in root package
A common Android mistake is putting @JvmOverloads on a custom View constructor with defStyleAttr: Int = 0. The generated 2-argument constructor then passes 0 instead of calling the framework's own 2-argument constructor, and the default style from the theme is lost (buttons stop looking like buttons, for example). For views that subclass a styled widget, write the constructors by hand, or use the widget's default style attribute (like R.attr.buttonStyle) as the default value.
Only add @JvmOverloads to APIs that Java code calls. Every generated method is part of your binary API, and pure Kotlin callers don't need them.
Overloading operators
Operators such as a + b, a[i], a() and a += b are calls to functions marked with operator (plus, get, invoke, plusAssign). They follow the same overload rules as above: you can declare plus(other: Vector) and plus(scalar: Double) on the same class. The details, including which names map to which operators, are covered in Operator functions, and DSL use in Using operators with lambdas.
Summary
- Overloads must differ in parameter types or count; the return type doesn't count.
- The compiler picks the most specific applicable candidate using static types. Smart casts count, runtime types don't.
- Members win over extensions, and closer scopes win over farther ones, even when the farther candidate is more specific.
- Fixed parameters beat
vararg, concrete types beat generics, and a candidate that doesn't need defaults beats one that does. - There's no implicit numeric widening, but integer literals can become
Long. - Erasure means
List<Int>/List<String>,T/T?and function types with different return types clash on the JVM. Use@JvmName. - Prefer default arguments to overload chains, and use overloads when the parameters have different types or meanings.
- Use
@JvmOverloadsto generate Java-friendly overloads from defaults. It drops parameters from the end and isn't allowed on abstract functions.