Skip to content

Instantly share code, notes, and snippets.

@awwsmm
Created November 8, 2021 12:04
Show Gist options
  • Save awwsmm/7ba319387bfef84f7422ad6150dede3b to your computer and use it in GitHub Desktop.
Save awwsmm/7ba319387bfef84f7422ad6150dede3b to your computer and use it in GitHub Desktop.
Java's try-with-resources pattern, but in Scala.
trait SourceUtils {
/**
* Opens a `resource`, passes it to the given function `f`, then
* closes the resource, returning the value returned from `f`.
*
* Example usage:
* {{{
* val myString: String =
* using(scala.io.Source.fromFile("file.name")) { source =>
* source.getLines.mkString
* }
* }}}
*
* @param resource closeable resource to use, then close
* @param f function which maps the resource to some return value
* @tparam T type of the resource to be opened / closed
* @tparam U type of the return value
* @return the result of the function `f`
*/
def using[T <: AutoCloseable, U](resource: => T)(f: T => U): U = {
scala.util.Try(resource).fold(throw _, source => {
val result = f(source)
source.close()
result
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment