Function Overloading in Kotlin

In this tutorial, we will learn about the Function overloading in Kotlin. Same as Java Methods we can overload function in Kotlin. To overload a function in Kotlin, the function must have the same name and parameter lists should be different(in data type or in numbers). Check out the following example program.

Example Program:

//overloaded function
fun addition(num1: Int, num2: Int): Int{
  return num1+num2
}

//overloaded function
fun addition(num1: Double, num2: Double): Double{
  return num1+num2
}

fun main (args: Array<String>){
    var ans=addition(10,20) //calling the addtion function with int values
    println("Ans = "+ans)
    var ans2=addition(21.5,11.2) //calling the addtion function with double values
    println("Ans = "+ans2)
}

Output:

Ans = 30
Ans = 32.7

As in above example, you can see particular function is invoking on function call according to the parameter we are passing while calling the function,

Spread the love
Scroll to Top