each_line do |line| in Scala
I’m so used to the each_line idiom in Ruby, I felt utterly lost in Scala without it.
Here’s an approximation of it, though I’d love to hear that there’s an even more scala-ish (scalic?) way of doing this:
def eachline(stream : InputStream)(f : String => Unit) {
val buf = new BufferedReader( new InputStreamReader( stream ) )
var line = buf.readLine
while (line != null) {
f(line)
line = buf.readLine
}
}
I use this with a block as so:
eachline(System.in) { line =>
Console.println(line)
}
Not bad, but it could be better, I think. Can I tickle this to be a method on streams, instead of a funny little function sitting on its own?




March 29th, 2007 at 11:37 am
Aaron,
Here’s a little modification of your code…
def eachlineT(f : String => T): Seq[T] = { val buf = new BufferedReader( new InputStreamReader( stream ) ) val ret = new ListBuffer[T] def readLine { val line = buf.readLine if (line ne null) { ret = f(line) readLine(buf, ret, f) } }
readLine(buf, ret, f) ret }
It’s “var-free”, plus it allows you to build lists of the input.
Thanks,
David