rakesh jayaram
rakesh jayaram

Reputation: 63

How to return the calling object in scala

The object below has to called using cleanup and later start. How to return the calling object back to the next method to make sure all the variables set are still available, without creating a new object instance.

class a =
{
    val z ="Hello"

    def remove(): com.hello.a =
    {
        return ? /* how to return the same object type A , so that start() definition gets the correct object**/
    }

    def start () : unit = 
    {      
        /**buch of tasks **/
    }
}

a.remove().start()

Upvotes: 0

Views: 1494

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31212

in scala this is reference to current instance(like in java).

example,

class SomeClass {

  def remove(): SomeClass = {
    println("remove something")
    this
  }

  def start(): Unit = {
    println("start something")
  }
}

new SomeClass().remove().start()

outputs

remove something
start something

.remove().start() looks little odd here, you might instead want to define remove as private method and simply call start which removes before it starts.

example.

class SomeClass {
  val zero = "0"

  private def remove() = {
    println("remove something")
  }

  def start(): Unit = {
    remove()
    println("start something")
  }
}

new SomeClass().start()

or, you might want to define companion object which will call do removing stuffs and give you the instance,

   class SomeClass {
      val zero = "0"

      private def remove() = {
        println("remove something")
      }

      def start(): Unit = {
        println("start something")
      }
    }

    object SomeClass {

      def apply(): SomeClass = {
        val myclass = new SomeClass()
        myclass.remove()
        myclass
      }

    }

    SomeClass().start()

Upvotes: 1

Related Questions