Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next element from stream in Scala

Tags:

stream

scala

Is there a method or way to get each next element from a stream?

For example if there is a stream looking like

def natural: Stream[Long] = {
  def naturalHelper: Long => Stream[Long] = {
    n => n #:: naturalHelper(n+1)
  }
  naturalHelper(1)
}

val s = natural

I'm looking for something like s.next(), returning 2 on the first call, s.next() = 3 on the next call, and so on... without using var.

like image 924
Explicat Avatar asked Jul 28 '13 21:07

Explicat


1 Answers

Make it an iterator

val s = natural.iterator
s.next()
s.next()
like image 101
0__ Avatar answered Oct 17 '22 18:10

0__