我还没有理解下面的代码片断为什么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