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 [Last updated : March 11, 2023]

Scala – Passing an Object as an Argument

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.

Scala code to pass an object as an argument

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 »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.