Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Scala - Method Overloading - Testingpool

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
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...