Skip to content

Instantly share code, notes, and snippets.

@apivovarov
Last active June 5, 2016 05:12
Show Gist options
  • Save apivovarov/3792d7cee70ed1d1332593a94c8af7f0 to your computer and use it in GitHub Desktop.
Save apivovarov/3792d7cee70ed1d1332593a94c8af7f0 to your computer and use it in GitHub Desktop.
Automatic Resource Management
/**
* Monad to work with AutoClosables
* Automatic Resource Management
*
* Example:
* val lines = Arm(new FileInputStream("/my.txt")).map { stream =>
* Source.fromInputStream(stream)("UTF-8").getLines
* }
*
*/
object Arm {
def apply[A <: AutoCloseable](c: A) = new AutoCloseableWrapper(c)
}
class AutoCloseableWrapper[A <: AutoCloseable](protected val c: A) {
def map[B](f: (A) => B): B = {
try {
f(c)
} finally {
c.close()
}
}
def foreach(f: (A) => Unit): Unit = map(f)
// Not a proper flatMap.
def flatMap[B](f: (A) => B): B = map(f)
// Hack :)
def withFilter(f: (A) => Boolean) = this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment