【问题标题】:Make an Iterator on values from function calls对来自函数调用的值创建一个迭代器
【发布时间】:2020-05-13 17:12:14
【问题描述】:

让有一个函数foo(): Int。例如,每次调用 foo() 返回不同的值。只是为了说明:

var i: Int = 0

def foo(): Int = {
    i += 1
    i
}

我想遍历这些值。实际上,我想构造一个Iteratorit,以便重复调用foo() 计算的每个调用it.next()。怎么做?

【问题讨论】:

    标签: scala iterator


    【解决方案1】:

    正如我常说的,Scaladoc 是你的朋友。

    Iterator.continually(foo())
    

    【讨论】:

      【解决方案2】:

      Luis 的回答更好,但这里有另一种方法:

      new Iterator[Int] {
        override def hasNext: Boolean = true
        override def next: Int = foo()
      }
      

      【讨论】:

        猜你喜欢
        • 2018-05-20
        • 2012-11-18
        • 2016-07-24
        • 1970-01-01
        • 2021-12-06
        • 2021-10-15
        • 2011-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多