2017-07-24 54 views
0

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

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

a.remove().start() 

回答

1

in scala this是对当前实例的引用(如在java中)。

例如,

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

或者,你可能希望定义同伴对象,它会调用做删除的东西,给你的情况下,

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