Skip to content

Instantly share code, notes, and snippets.

@SethTisue
Created May 24, 2011 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SethTisue/989258 to your computer and use it in GitHub Desktop.
Save SethTisue/989258 to your computer and use it in GitHub Desktop.
eliminating a mutable buffer
import java.io._
def userStream =
new BufferedReader(
new InputStreamReader(
new FileInputStream("/etc/passwd")))
// imperative style
def linesI(s: BufferedReader): List[String] = {
val buf = new collection.mutable.ListBuffer[String]
while(true) {
val line = s.readLine()
if(line == null)
return buf.toList
buf += line
}
error("wtf")
}
// functional style
def linesF(s: BufferedReader): List[String] =
Iterator.continually(s.readLine()).takeWhile(_ != null).toList
linesI(userStream).foreach(println)
linesF(userStream).foreach(println)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment