Created
January 17, 2017 01:11
-
-
Save xhoong/b2912a27cbff5b9cde603a2612917ee6 to your computer and use it in GitHub Desktop.
Functional output stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Used for reading/writing to database, files, etc. | |
* Code From the book "Beginning Scala" | |
* http://www.amazon.com/Beginning-Scala-David-Pollak/dp/1430219890 | |
* http://stackoverflow.com/a/5218279 | |
*/ | |
def using[A <: {def close(): Unit}, B](param: A)(f: A => B): B = | |
try { f(param) } finally { param.close() } | |
def writeToFile(fileName:String, data:String) = | |
using (new FileWriter(fileName)) { | |
fileWriter => fileWriter.write(data) | |
} | |
def appendToFile(fileName:String, textData:String) = | |
using (new FileWriter(fileName, true)){ | |
fileWriter => using (new PrintWriter(fileWriter)) { | |
printWriter => printWriter.println(textData) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment