Last active
June 5, 2016 05:12
-
-
Save apivovarov/3792d7cee70ed1d1332593a94c8af7f0 to your computer and use it in GitHub Desktop.
Automatic Resource Management
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
/** | |
* 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