SkyWalker
SkyWalker

Reputation: 14309

How to properly use Stream's iterate and takeWhile constructs?

In Scala 2.12.x I have the following example but it doesn't produce the expected result:

val result = Stream.iterate(0)(_ + 10).takeWhile(_ < 100)
println(result)

// outputs:
// Stream(0, ?)

// while I expected:
// Stream(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, ?)

What am I doing wrong here?

Upvotes: 2

Views: 112

Answers (1)

Stu Redman
Stu Redman

Reputation: 282

Your stream won't be materialized until you convert it to non-lazy colection:

Stream.iterate(0)(_ + 10).takeWhile(_ < 100).toList

Upvotes: 2

Related Questions