ADVERTISEMENT
ADVERTISEMENT

Scala program to pass an object as an argument

Here, we are going to learn how to pass an object as an argument in Scala programming language?
Submitted by Nidhi, on June 28, 2021

Problem Solution:

Here, we will create a method that accepts the object of class as an argument to add the value of data member of current object with the value of data member of the specified object and print the result on the console screen.

Program/Source Code:

The source code to pass an object as an argument is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to pass an object as an argument

class Demo {
  var num: Int = 0;

  def addObj(obj: Demo) {
    var result: Int = 0;
    result = this.num + obj.num;
    printf("Result : %d\n", result);
  }

  def setVal(n: Int) {
    num = n;
  }
}

object Sample {
  def main(args: Array[String]) {
    // Create objects of Demo class
    var obj1 = new Demo()
    var obj2 = new Demo()

    obj1.setVal(10);
    obj2.setVal(20);

    obj1.addObj(obj2);
  }
}

Output:

Result : 30

Explanation:

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

Here, we created a class Demo that contain two methods setVal() and addObj(). The setVal() method is used to set the value of data members. The addObj() method is used to add the value of the data member of the current object with the value of the data member of the specified object and print the result on the console screen.

In the main() function, we created two objects and add the value of both, and printed the result on the console screen.

Scala Classes & Objects Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


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.