Skip to content

Instantly share code, notes, and snippets.

@amaya382
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amaya382/7c10329885c991816c2a to your computer and use it in GitHub Desktop.
Save amaya382/7c10329885c991816c2a to your computer and use it in GitHub Desktop.
loan pattern
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