Scala program to implement cascaded method call

Here, we are going to learn how to implement cascaded method call in Scala programming language?
Submitted by Nidhi, on June 28, 2021 [Last updated : March 11, 2023]

Scala – Implementing Cascaded Method Calls

Here, we will create a class that contains three methods. Each method will return the object of the same class. To return the object of the class, we used this object. By returning an object from each method, we can implement a cascaded method call.

Scala code to implement cascaded method calls

The source code to implement the cascaded method call is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to implement cascaded method call

class Demo {
  def method1(): Demo = {
    println("Method1 called");
    return this;
  }

  def method2(): Demo = {
    println("Method2 called");
    return this;
  }

  def method3(): Demo = {
    println("Method3 called");
    return this;
  }
}

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

    //Cascaded method call.
    obj.method1().method2().method3();
  }
}

Output

Method1 called
Method2 called
Method3 called

Explanation

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

Here, we created a class Demo with three methods Method1(), Method2(), Method3(). All methods return the object of the same class using this object to implement the cascaded method class.

In the main() function, we created an object of the Demo class and then call all methods using the single object in a single line.

Scala Classes & Objects Programs »





Comments and Discussions!

Load comments ↻





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