Newer versions of Scala have Using, but as far as I know, it isn’t backported, as least not to 2.11. So, I am using a homemade version that until recently depended on this trick
protected type Closeable = {def close() : Unit}
so that anything that can close() works with the code. However, this apparently involves runtime reflection which triggers a security violation in newer versions of Java (depending on which jar the class comes from). So, I backed off from that version of Closeable to java.io.Closeable or java.lang.AutoCloseable. That works fine except for Scala 2.11 in which Source (and BufferedSource) is not Closeable. To get around that, I’m converting Source with an implicit conversion to something that can (auto)close. To get that, I unfortunately have to use an extra import statement in any file that needs to automatically close a Source. I’d like to not do that.
Does anyone have a way of adding close() to Scala 2.11 Source that can work more transparently? Here’s an outline of some of the code:
object Closer {
def autoClose3[Resource, Result](resource: Resource)(closer: () => Unit)(function: Resource => Result): Result = ???
def autoClose[Resource <: AutoCloseable, Result](resource: Resource)(function: Resource => Result): Result = ??? // call to autoClose3
implicit class AutoCloser[Resource <: AutoCloseable](resource: Resource) {
def autoClose[Result](function: Resource => Result): Result =
Closer.autoClose(resource)(function)
}
// In Scala 2.11, Source does not inherit from Closeable, so one has to tell Closer how to close() it.
// This requires the extra import which I would like to avoid.
implicit class AutoSource[Resource <: Source](resource: Resource) {
def autoClose[Result](function: Resource => Result) =
Closer.autoClose3(resource)(() => resource.close())(function)
}