Iterator.continually vs Scala中的while(..)

时间:2014-04-23 23:55:16

标签: scala iterator

    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

VS

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

具有完全相同的行为。它们在引擎盖下是否相同?

1 个答案:

答案 0 :(得分: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)

但我想这并不是你想要从你的例子中做到的。

相关问题