C# has using
with the IDisposable
interface. Java 7+ has identical functionality with try
and the AutoCloseable
interface. Scala lets you choose your own implementation to this issue.
scala-arm seems to be the popular choice, and is maintained by one of the Typesafe employees. However, it seems very complicated for such a simple behavior. To clarify, the usage instructions are simple, but understanding how all that code is working internally is rather complex.
I just wrote the following super simple ARM solution:
object SimpleARM {
def apply[T, Q](c: T {def close(): Unit})(f: (T) => Q): Q = {
try {
f(c)
} finally {
c.close()
}
}
}
Overview. In Java, we can use the try-with-resources statement to automatically close all resources that we need in our code. This statement works with every class that implements the AutoCloseable interface. Unfortunately, such a feature does not exist in Scala.
In the try-with-resources method, there is no use of the finally block. The file resource is opened in try block inside small brackets. Only the objects of those classes can be opened within the block which implements the AutoCloseable interface, and those objects should also be local.
It makes the code more readable and the writer reference is local to the try block so you cannot access it outside of the try block. In this way, Java guarantees that there cannot be any illegal accesses after closing the connection.
automatic resource management or try-with-resources is a new exception handling mechanism that was introduced in Java 7, which automatically closes the resources used within the try-catch block.
Your approach with a single simple loan pattern is working fine as long as you don't need to work with several resources, all needing to be managed. That's allowed with scala-arm monadic approach.
import resource.managed
managed(openResA).and(managed(openResB)) acquireFor { (a, b) => ??? }
val res = for {
a <- managed(openResA)
b <- managed(openResB)
c <- managed(openResC)
} yield (a, b, c)
res acquireAndGet {
case (a, b, c) => ???
}
Main functions to know in scala-arm is resource.managed
and .acquired{For,AndGet}
, not really complex btw.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With