2016-09-06 70 views
0

我希望將var/val的值從一種方法傳遞給另一種方法。
例如,我有在Scala中相同Object的2個方法之間傳遞值

object abc { 

    def onStart = {  
    val startTime = new java.sql.Timestamp(new Date()) 
    } 

    def onEnd = { 
    //use startTime here 
    } 
} 

電話:

onStart() 
executeReports(reportName, sqlContexts) 
onEnd() 

這裏onStart()onEnd()是作業監視功能executeReports()
executeReports()在5個報告中循環運行。

我一直在使用全局變量一樣

object abc{ 

    var startTime : java.sql.Timestamp = _ 

    def onStart = {  
    startTime = new java.sql.Timestamp(new Date()) 
    } 

    def onEnd = { 
    //use startTime here 
    } 

} 

,但與此有關的缺點是當循環執行下一個報告試過了,startTime不會改變。

我也嘗試過使用Singleton類,它對我也不起作用。

我的要求是每個迭代都有一個startTime,即每個報告。 任何想法都歡迎在這裏。如果需要,我會很樂意提供有關我的要求的更多說明。

回答

5

對此的常見Scala解決方案是編寫一個封裝其他函數並在內部執行設置和關閉的函數。

def timeit[T](fun: => T): T = { 
    val start = System.currentTimeMillis //Do your start stuff 
    val res = fun 
    println (s"Time ${System.currentTimeMillis - start}") // Do your end stuff 
    res 
} 
+0

謝謝RussS!在我的情況下,我被綁定到設計上,並且我無法做出任何更改..但是我愛你的答案。 :)它整潔有效,以及 – underwood

1

RussS有更好的解決方案,但如果由於某種原因,你執着於你所描述的設計,你可以嘗試使用可變val,即一個可變的集合。

我得到這個編譯和通過一些小測試。

object abc { 
    private val q = collection.mutable.Queue[java.sql.Timestamp]() 

    def onStart = { 
    q.enqueue(new java.sql.Timestamp(java.util.Calendar.getInstance().getTime.getTime)) 
    } 

    def onEnd = { 
    val startTime = q.dequeue 
    } 
} 
+0

使用隊列是一個很好的!謝謝@ jwvh – underwood

0

根據您的要求,最好這樣做。

case class Job(report: List<Report>) { 
def execute // does the looping on Report by calling start and call end to generate monitoring data 

private def start // iterate over each Report and calls it's execute method 

private def end // iterate over each Report and uses startTime and executionTime to generate monitoring data. 
} 

abstract class Report { 
var startTime: DateTime //Time started for the report 
def doReport // unimplemented method that does the report generation. 
def execute // first set stateTime to Now then call doReport, lastly calculate executionTime 
} 

報告的子類型應該實現doReport,它可以做實際的報告。

您還可以更改Job.execute方法接受

report: List<Report> 

,這樣你可以有一個單工作(可以肯定的,開始和結束將是你把所有工作一樣。)