2014-04-23 37 views
1
def task() { 
     Thread.sleep(60*1000) // update lru cache every minute 
     // do some compute-intensive task here to populate lru cache 
     println("LRU Updated!") 
    } 

    new Thread { 
    override def run = while(true) task() 
    }.start 

而(..)VSIterator.continually VS斯卡拉

Iterator.continually(task()).dropWhile(_=>true) 

具有完全相同的行爲。它們在引擎蓋下等價嗎?

+3

這取決於你的意思是「等價」。它們絕對不會導致相同的字節碼,「持續」版本的開銷更大。 – wingedsubmariner

回答

0

Iterator.continually對於獲得迭代器非常有用,您可以像使用僞集合一樣使用迭代器,以獲得非副作用結果。在這裏你正在做println,所以continually是一個不錯的糖,但它並沒有給你任何東西。 如果你有這樣的事情:

def task() { 
    Thread.sleep(60*1000) // update lru cache every minute 
    // do some compute-intensive task here to populate lru cache 
    "LRU Updated!" 
} 

要應用的副作用,你仍然可以使用的線程,但是你不能夠做​​更多的事情(沒有更復雜的代碼)。

new Thread { 
override def run = while(true) println(task()) 
}.start 

如果你想變換的輸出,或將其推到另一個呼叫,或撰寫它等於是一個迭代器將是一個更好的抽象:

Iterator.continually(task()).map(x => s"$x Yay!").take(100) 

但我想這不是真的你想從你的例子中做什麼。