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

Scala – Method Returning an Object

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.

Scala code to create a method returning an object

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();



Method returning object
Hello World
Hello World


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 »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.