views:

97

answers:

2

I'm attempting to create an infinite stream of strings from readLine calls:

import java.io.{BufferedReader, InputStreamReader}
val in = new BufferedReader(new InputStreamReader(System in))
val input: Stream[String] = Stream.cons(in readLine, input)

But it appears that the readLine call isn't being called lazily. Immediately after entering that code, the readLine expects input then the Stream becomes an infinite list of that same input. Is it possible to accomplish what I have in mind?

+3  A: 

See the example at Stream. Note that the lazy thunk is in the tail, not the head. Each time the thunk is invoked it should return the next cons (including the next thunk which in turn should supply the next cons incl....)

Here is the signature for Stream.cons: <http://www.scala-lang.org/docu/files/api/scala/collection/immutable/Stream$$cons$.html&gt;. Note the thunk (=> Stream) as the 2nd argument to apply.

pst
+7  A: 
import java.io.{BufferedReader, InputStreamReader}
val in = new BufferedReader(new InputStreamReader(System in))
val input = Stream.continually(in readLine)
Eastsun