Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active December 15, 2015 09:09
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 loicdescotte/5235958 to your computer and use it in GitHub Desktop.
Save loicdescotte/5235958 to your computer and use it in GitHub Desktop.
printToFile function

Higher order function to write stuffs in a file, with automatic resources management

Code

  def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) {
    val p = new java.io.PrintWriter(f)
    try { op(p) } finally { p.close() }
  }

Usage example

val data = Array("here","is","what","I","want", "to", "print")

printToFile(new File("example.txt"))(p => {
  data.foreach(p.println)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment