Stream of readLines
Asked Answered
A

2

7

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?

Amadavat answered 22/7, 2010 at 6:11 Comment(0)
R
11
import java.io.{BufferedReader, InputStreamReader}
val in = new BufferedReader(new InputStreamReader(System in))
val input = Stream.continually(in readLine)
Rachaba answered 22/7, 2010 at 8:58 Comment(1)
Do you not need to close the stream?Abessive
L
3

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.

Lipoprotein answered 22/7, 2010 at 6:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.