如何在scala中返回调用对象

如何在scala中返回调用对象,scala,Scala,必须使用“清理”和“以后启动”调用下面的对象。如何将调用对象返回到下一个方法,以确保所有变量集仍然可用,而无需创建新的对象实例 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**/

必须使用“清理”和“以后启动”调用下面的对象。如何将调用对象返回到下一个方法,以确保所有变量集仍然可用,而无需创建新的对象实例

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()
在scala中,这是对java中当前instancelike的引用

例如

class SomeClass {

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

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

new SomeClass().remove().start()
输出

remove something
start something
.remove.start在这里看起来有点奇怪,您可能希望将remove定义为私有方法,并简单地调用start,它在开始之前删除

例如

class SomeClass {
  val zero = "0"

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

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

new SomeClass().start()
或者,您可能需要定义同伴对象,该对象将调用do removing Stuff并为您提供实例

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