我還沒有理解下面的代碼片斷爲什麼afterDelay(0) {...}
,一個本地定義的函數可以存儲到議程?有人能幫我理解run
函數中的afterDelay(0) {...}
嗎?斯卡拉,將本地定義的函數傳遞給列表?
abstract class Simulation {
type Action =() => Unit
case class WorkItem(time: Int, action: Action)
private var curtime = 0
def currentTime: Int = curtime
private var agenda: List[WorkItem] = List()
private def insert(ag: List[WorkItem], item: WorkItem): List[WorkItem] = {
if (ag.isEmpty || item.time < ag.head.time) item :: ag
else ag.head :: insert(ag.tail, item)
}
def afterDelay(delay: Int)(block: => Unit) {
val item = WorkItem(currentTime + delay,() => block)
agenda = insert(agenda, item)
}
private def next() {
(agenda: @unchecked) match {
case item :: rest =>
agenda = rest
curtime = item.time
item.action()
}
}
def run() {
afterDelay(0) {
println("*** simulation started, time = "+
currentTime +" ***")
}
while (!agenda.isEmpty) next()
}
}
「這就是當函數結果()=>塊被調用時,這裏發生在afterDelay函數返回後的某個點上(在item.action())上。」 - 在item.action()中調用afterDelay後?我感覺println(「*** simulation started,time =」+ currentTime +「***」),即afterDelay的()=>單位參數在item.action() – chen
否,'afterDelay'在被調用時被調用。它創建一個* new *函數對象(它成爲'WorkItem.action'),它關閉'block'參數(將其綁定到閉包中)。然後它創建新的'WorkItem',並將其排隊;當* new *函數被調用時(通過其他地方的'item.action()'),那麼它會導致評估名稱參數(這將調用'println')。請將它與傳入'()=> Unit'進行比較。 – 2012-05-08 05:08:38