Function Overloading and Function Formatting
Explore function overloading, infix notation, and precise formatting techniques.
We'll cover the following...
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.
Press + to interact
@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)) // Intprintln(a(18L)) // Longprintln(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 ...