Search⌘ K
AI Features

Function Overloading and Function Formatting

Explore how to define and use overloaded functions in Kotlin with different parameters, utilize infix syntax for cleaner calls, and apply formatting best practices to keep your code readable and maintainable.

Function overloading

In Kotlin, we can define functions with the same name in the same scope (file or class) as long as they have different parameter types or a different number of parameters. This is known as function overloading. Kotlin decides which function to execute based on the types of the specified arguments.

Kotlin 1.5
@Suppress("UNUSED_PARAMETER")
fun a(a: Any) = "Any"
@Suppress("UNUSED_PARAMETER")
fun a(i: Int) = "Int"
@Suppress("UNUSED_PARAMETER")
fun a(l: Long) = "Long"
fun main() {
println(a(1)) // Int
println(a(18L)) // Long
println(a("ABC")) // Any
}

Remember: The @Suppress("UNUSED_PARAMETER") annotation suppresses warnings about unused parameters in Kotlin code. It instructs the compiler to ignore warnings about declared but unused parameters.

Infix syntax

Methods with a single parameter can use the infix modifier, which allows a special kind of function call: ...