ADVERTISEMENT
ADVERTISEMENT

Scala program to create a method returning an object

Here, we are going to learn how to create a method returning an object in Scala programming language?
Submitted by Nidhi, on June 28, 2021

Problem Solution:

Here, we will create a class that contains two methods. And, we will implement a method that will return an object of the same class.

Program/Source Code:

The source code to create a method returning object is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to create a method 
// returning an object

class Demo {
  def retObj(): Demo = {
    println("Method returning object");
    return this;
  }

  def sayHello() {
    println("Hello World");
  }

}

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

    obj1.sayHello();
    obj2.sayHello();
  }
}

Output:

Method returning object
Hello World
Hello World

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 contains two methods retObj() and sayHello(). The retObj() method returns the object of the same class and the sayHello() method prints the "Hello World" message on the console screen.

In the main() function, we created an obj1 object of the Demo class and called retObj() method. It returns the object, which is assigned to the obj2 object. Then we called the sayHello() method from both objects and print messages 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.