ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Scala program to implement method overloading based on different types of arguments

Here, we are going to learn how to implement method overloading based on different types of arguments in Scala programming language?
Submitted by Nidhi, on July 20, 2021

Problem Solution:

Here, we will create a class and implement method overloading by creating methods with different types of arguments to add specified numbers and print the result on the console screen.

Program/Source Code:

The source code to implement method overloading based on different types of arguments is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to implement method overloading 
// based on different types of arguments

class Calc {
  def AddNumbers(num1: Int, num2: Int) {
    var result: Int = 0;

    result = num1 + num2;
    printf("Sum of integer numbers is: %d\n", result);
  }
  def AddNumbers(num1: Float, num2: Float) {
    var result: Float = 0;

    result = num1 + num2;
    printf("Sum of float numbers is: %f\n", result);
  }
}

object Sample {
  def main(args: Array[String]) {
    var obj = new Calc();

    obj.AddNumbers(10, 20);
    obj.AddNumbers(10.4f, 20.5f);
  }
}

Output:

Sum of integer numbers is: 30
Sum of float numbers is: 30.900000

Explanation:

In the above program, we used an object-oriented approach to create the program. And, we created an object Sample.

Here, we created a class Calc. In the Calc class, we implemented method overloading by creating two AddNumbers() methods with different types of arguments. The AddNumbers() method is used to add specified arguments and print the result on the console screen.

In the main() function, we created an object of the Calc class and called both methods with arguments, and printed the result on the console screen.

Scala Classes & Objects Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.