Make an Iterator on values from function calls

Viewed 52

Let there is a function foo(): Int. For example, each call foo() returns different values. Just to illustrate:

var i: Int = 0

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

I would like to iterate through these values. Actually, I would like to construct an Iterator it so that each call it.next() computed by foo() called repeatedly. How it can be done?

2 Answers

As I always say, the Scaladoc is your friend.

Iterator.continually(foo())

Luis's answer is better, but here's another way to do it:

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