Kotlin Function Overloading

Kotlin supports function overloading. Function overloading means the ability to define more than one function with the same name. Now two questions may arise in your mind. One, why do we have to define two functions with the same name when we can always give different names. Two, if we define more than one function with the same name, how does the compiler know which function to call, when it encounters a call to the overloaded function? We’ll look at these questions separately and I’m sure you’ll be able to find answers when you completely read this post.

kotlin function overloading

It is recommended that you read my post on functions before reading this.

Need of function overloading

Suppose we want to write a function for calculating the square of a number. In Kotlin, as you know, there are several types of numbers like Int, Double etc. So when we want to write such a function, we have to write separate functions for each type.

Like this:

fun main(args: Array<String>) {
    println(squareInt(34))
    println(squareDouble(62.34))
}

fun squareInt(num: Int) = num * num
fun squareDouble(num: Double) = num * num

Imagine that the one who writes the main function is a different person. He has to know the names of functions for different types of numbers.

Function overloading provides an easy fix to this. We write functions with the same name:

fun main(args: Array<String>) {
    println(square(34))
    println(square(62.34))
}

fun square(num: Int) = num * num
fun square(num: Double) = num * num

Now, as you can see, the two functions use the same name. What is the difference? One accepts an Int argument while the other accepts a Double value. The compiler uses this distinction to resolve calls to the function.

Resolution of the call of overloaded function

The number of parameters is also a way to distinguish overloaded functions. The compiler checks for a match at compile time and when a match is found, the compiler calls that particular function. It’s a very useful feature in Kotlin.

See the program to find absolute value of a number using function overloading.

fun main(args: Array<String>) {
    println(abs(-11))
    println(abs(-23.723))
    println(abs(92.65))
}

fun abs(num: Int) = if (num < 0) -num else num
fun abs(num: Double) = if (num < 0) -num else num

The function abs() is overloaded. The functions are defined as one-line functions. So, it is really concise. The function returns -num if the number is less than zero. Otherwise, it returns the number itself.

That’s all about function overloading in Kotlin.
Comments and feedback are always welcome.
Happy Coding đŸ™‚

« Back to the index of Kotlin tutorial

Add a Comment

Your email address will not be published. Required fields are marked *