Function Overloading means, when two or more methods have the same name but different parameters.
Below are two types of difference in parameters that Kotlin considers for method overloading :
Now, let's see the first way of operator Overloading.
fun add(firstNumber: Int, secondNumber: Int, thirdNumber: Int): Int
fun add(firstNumber: Int, secondNumber: Int): Int
fun add(firstNumber: Int): Int
fun main(){ var firstNum: Int = 5 var secondNum: Int = 8 var thirdNum: Int = 2 var addedResult1: Int var addedResult2: Int addedResult1 = add(firstNum,secondNum) println("The added value of two numbers is : "+addedResult1) addedResult2 = add(firstNum,secondNum,thirdNum) println("The added value of three numbers is : "+addedResult2); } //Add method starts here. fun add(firstNumber: Int, secondNumber: Int): Int { var result: Int result = firstNumber + secondNumber return result } //Overloaded Add method starts here. fun add(firstNumber: Int, secondNumber: Int, thirdNumber: Int): Int { var result: Int result = firstNumber + secondNumber + thirdNumber return result }
addedResult1 = add(firstNum,secondNum)
addedResult2 = add(firstNum,secondNum,thirdNum)
fun add(firstNumber: Float, secondNumber: Float): Float
fun add(firstNumber: Int, secondNumber: Int): Int
fun main(){ var firstNum: Int = 5 var secondNum: Int = 8 var firstNumFloat: Float = 2.4F var secondNumFloat: Float = 9.5F var addedResult1: Int var addedResult2: Float addedResult1 = add(firstNum,secondNum) println("The added value of two numbers : "+addedResult1) addedResult2 = add(firstNumFloat,secondNumFloat) println("The added value of decimal numbers : "+addedResult2); } //Add method starts here. fun add(firstNumber: Int, secondNumber: Int): Int { var result: Int result = firstNumber + secondNumber return result } //Overloaded Add method starts here. fun add(firstNumber: Float, secondNumber: Float): Float { var result: Float result = firstNumber + secondNumber return result }
fun add(firstNumber: Int, secondNumber: Int): Int
fun add(firstNumber: Float, secondNumber: Float): Float
addedResult1 = add(firstNum,secondNum)
fun add(firstNumber: Int, secondNumber: Int): Int
addedResult2 = add(firstNumFloat,secondNumFloat)
fun add(firstNumber: Float, secondNumber: Float): Float