Introduction: Overloading Functions in Kotlin

Hello there, future coder! In this session, we will unravel function overloading in Kotlin. It's much like a multi-purpose gadget; it has different functionalities, all under one name. By the end of this lesson, you will have a firm understanding of what function overloading is, its purpose, and how to create overloaded functions in Kotlin. Ready? Let's get rolling!

Theory: Unwrapping Function Overloading

Function overloading is akin to a chef crafting dishes with unique ingredient combinations—you use different ingredients (parameters), but the dish's name (function name) remains the same.

In Kotlin, function overloading allows us to define multiple functions with the same name but different parameters. Kotlin chooses the appropriate function to execute based on the type or quantity of arguments, providing us with effective code organization and improved readability.

Practical: Overloading Functions with Different Parameter Types

Let's bring this concept to life.

Suppose we're developing an application for a display board. Sometimes we receive text to display (a String), and other times, a number (an Int).

Kotlin
fun display(input: String) {
    println("Calling display with String input: ${input}")
}

fun display(input: Int) {
    println("Calling display with Int input: ${input}")
}

fun main() {
    display("Hello, World!") // Prints "Calling display with String input: Hello, World!"
    display(12345) // Calling display with Int input: 12345
}

Our function named display proved useful in both cases, with each function executing as intended. This is function overloading with different parameter types!

Practical: Overloading Functions with Varying Numbers of Parameters

In another scenario, let's overload functions with varying numbers of parameters. If we want to add two or three numbers, we can define two add functions, each accepting a different number of parameters.

fun add(num1: Int, num2: Int): Int {
    return num1 + num2
}

fun add(num1: Int, num2: Int, num3: Int): Int {
    return num1 + num2 + num3
}

fun main() {
    println(add(1, 2))  // Calls first "add" function
    println(add(1, 2, 3)) // Calls second "add" function
}

Kotlin selects the correct overloaded function based on the number of arguments provided.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal