Search code examples
scalaiteratorunfold

How to produce a true `Iterator[Long]` in Scala


I came across this other post looking for a way to create an Iterator[Long].

Currently the Scala SDK does not have any Iterator constructor that produces an Iterator[Long].

Other collection types may (unverified) provide some kind of constructor, yielding a value from which a call to .iterator may produce a Iterator[Long], but how can you guarantee the 'lazy and forgetful' semantics of an Iterator?


Solution

  • Something like this lets you iterate through all (positive) Longs sequentially:

    Iterator.iterate(1L)(_ + 1)
    

    Alternatively, this produces an infinite iterator of random Longs:

    Iterator.continually(util.Random.nextLong) 
    

    This generates an infinite sequence of Fibonacci numbers:

    Iterator.iterate(1L -> 1L) { case (a,b) => (b, a+b) }.map(_._1)