Loom
Loom

Reputation: 9986

Make an Iterator on values from function calls

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?

Upvotes: 2

Views: 89

Answers (2)

user
user

Reputation: 7604

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()
}

Upvotes: 3

As I always say, the Scaladoc is your friend.

Iterator.continually(foo())

Upvotes: 4

Related Questions