Created
November 8, 2021 12:04
-
-
Save awwsmm/7ba319387bfef84f7422ad6150dede3b to your computer and use it in GitHub Desktop.
Java's try-with-resources pattern, but in Scala.
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
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