Skip to content

Instantly share code, notes, and snippets.

@fran0x
Last active June 16, 2016 06:01
Show Gist options
  • Save fran0x/c4c251a58f3b7e61a575f358321767b2 to your computer and use it in GitHub Desktop.
Save fran0x/c4c251a58f3b7e61a575f358321767b2 to your computer and use it in GitHub Desktop.
Utility code to auto-close resources (e.g. files)
// Control.using is used to automatically close any resource that has a close method
// note: from the book "Beginning Scala" (by David Pollak)
object Control {
import scala.language.reflectiveCalls
def using[A <: { def close(): Unit }, B](param: A)(f: A => B): B =
try {
f(param)
} finally {
param.close()
}
}
// example of usage
object Test extends App {
import Control._
def readLines(filename:String):Option[List[String]] = {
try {
val lines = using(io.Source.fromFile(filename)) {
source => (for (line <- source.getLines) yield line).toList
}
Some(lines)
} catch {
case e: Exception => None
}
}
if (args.length == 1) readLines(args(0)) match {
case Some(lines) => println(lines.length + " lines")
case None => println("No lines")
}
else println("No input")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment