Q:

Scala program to implement cascaded method call

belongs to collection: Scala Classes & Objects Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala program to create a method returning an obje... >>
<< Scala program to demonstrate the \'this\'...