C# has using with the IDisposable interface. Java 7+ has identical functionality with try and the AutoCloseable interface
This is the code I use:
def use[A <: { def close(): Unit }, B](resource: A)(code: A ⇒ B): B =
try
code(resource)
finally
resource.close()
Unlike Java try-with-resources, the resource doesn't need to implement AutoCloseable. Only a close() method is needed.
It only supports one resource.
Here is an example use with an InputStream:
val path = Paths get "/etc/myfile"
use(Files.newInputStream(path)) { inputStream ⇒
val firstByte = inputStream.read()
....
}