ReadLines stream

I am trying to create an endless stream of lines 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 looks like the readLine call isn't called lazily. Immediately after entering this code, readLine expects input, then Stream becomes an endless list of the same input. Is it possible to do what I mean?

+6
input scala stream lazy-evaluation
source share
2 answers
 import java.io.{BufferedReader, InputStreamReader} val in = new BufferedReader(new InputStreamReader(System in)) val input = Stream.continually(in readLine) 
+11
source share

See an example in Stream . Note that the lazy piece is in the tail, not in the head. Each time thunk is called, it should return the following minuses (including the next thunk, which in turn should contain the following minuses, including ...)

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

+3
source share

All Articles