C# has using with the IDisposable interface. Java 7+ has identical functionality with try and the AutoCloseable interface
An improvement I can recommend to the approach you suggested, which is:
def autoClose[A <: AutoCloseable, B](resource: A)(code: A ⇒ B): B = {
try
code(resource)
finally
resource.close()
}
Is to use:
def autoClose[A <: AutoCloseable, B](resource: A)(code: A ⇒ B): Try[B] = {
val tryResult = Try {code(resource)}
resource.close()
tryResult
}
IMHO having the tryResult which is an Try[B], will allow you an easier control flow later.