Created
October 13, 2010 01:00
-
-
Save eugener/623213 to your computer and use it in GitHub Desktop.
Equivalent of C# using keyword. Automatically closes any resource which has a close method. Capable of returning a value
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
object Controls { | |
type CloseableResource = { def close() } | |
/** | |
* Equivalent of C# using keyword. Automatically closes any resource which has a close method. | |
* Capable of returning a value | |
* @param T resource which has a close() method | |
* @param M result | |
*/ | |
def using[ T <: CloseableResource, M ](resource: T)(block: T => M ): M = { | |
require( resource != null, "non-null resource is required" ) | |
try { | |
block(resource) | |
} finally { | |
closeResource(resource) | |
} | |
} | |
/** | |
* Multiple resource version | |
*/ | |
def using[T <: CloseableResource, M](resources: T*)(block: Seq[T] => M): M = { | |
try { | |
block(resources) | |
} finally { | |
resources.foreach(closeResource) | |
} | |
} | |
/** | |
* Mutes closing exceptions | |
*/ | |
private[this] def closeResource[ T <: CloseableResource ] ( resource: T ): Unit = { | |
try { | |
resource.close | |
} catch { | |
case e => e.printStackTrace | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment