6

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.

1 Answer 1

11

Make it an iterator

val s = natural.iterator
s.next()
s.next()
Sign up to request clarification or add additional context in comments.

2 Comments

Right on. And if that's the only thing you plan on doing with the Stream, you probably shouldn't be using a Stream at all, since Streams save results and will eventually eat up all of your memory.
I agree with @AmigoNico any method with counter inside will do the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.