Scala – Method Overloading
In previous post, we have seen what is auxiliary constructor . Now, let’s understand the method overloading in scala.
What is method overloading?
When a class can have multiple methods with same name but different no. of parameters or different data type, will be called as method overloading. We will understand that with an example.
Method overloading with different parameters:
As you can see below , Addition class have 2 methods named add different parameters. We have created an object name obj and called both of the methods.
package main.com.testingpool
object TestAddition extends App{
var obj = new Addition
obj.add(2,3) //Output - 5
obj.add(2,3,4) //Output - 9
}
class Addition {
//add method with 2 parameters
def add(a:Int,b:Int): Unit ={
println(a+b)
}
//add method with 3 parameters
def add(a:Int,b:Int,c:Int): Unit ={
println(a+b+c)
}
}
Output:
5
9
Method overloading with different datatypes:
In the below example, we have multiple methods with same name and same no. of parameters but different data types.
package main.com.testingpool
object TestAddition extends App{
var obj = new Addition
obj.add(2,3)
obj.add(2.5,3.5)
}
class Addition {
//add method with 2 parameters and data type is Int
def add(a:Int,b:Int): Unit ={
println(a+b)
}
//add method with 2 parameters and data type is Double
def add(a:Double,b:Double): Unit ={
println(a+b)
}
}
Output:
5
6.0