Last active
August 29, 2015 14:11
-
-
Save amaya382/7c10329885c991816c2a to your computer and use it in GitHub Desktop.
loan pattern
This file contains hidden or 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
class Loan[T <: {def close()}] private(resources: T) { | |
def map[U](func: T => U): Option[U] = | |
try { | |
Option(func(resources)) | |
} catch { | |
case ex: Throwable => | |
ex.printStackTrace() | |
None | |
} finally { | |
if (resources != null) | |
resources.close() | |
} | |
def flatMap[U](func: T => Option[U]): Option[U] = | |
try { | |
func(resources) | |
} catch { | |
case ex: Throwable => | |
ex.printStackTrace() | |
None | |
} finally { | |
if (resources != null) | |
resources.close() | |
} | |
} | |
object Loan { | |
def apply[T <: {def close()}](value: T) = new Loan(value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment