Ukonu
Ukonu

Reputation: 73

Stream of readLines

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?

Upvotes: 7

Views: 3931

Answers (2)

Eastsun
Eastsun

Reputation: 18859

import java.io.{BufferedReader, InputStreamReader}
val in = new BufferedReader(new InputStreamReader(System in))
val input = Stream.continually(in readLine)

Upvotes: 11

user166390
user166390

Reputation:

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>. Note the thunk (=> Stream) as the 2nd argument to apply.

Upvotes: 3

Related Questions