The backing implementation of a managed resource.
The backing implementation of a managed resource. For a full explanation of how this is commonly extended, see the ManagedResource documentation.
type of the contained resource
An automatically managed resource which is closed before the code block handling it returns.
An automatically managed resource which is closed before the code block handling it returns. This is intended to be used in a for-comprehension such as:
for (x <- new FooResource().auto) { // ...code using x... }
which will call x.close()
(or an equivalent method via an AutoResource subclass)
when the code block goes out of scope. It is also legal to use the monad methods directly,
such as the following equivalent code to the above:
new FooResource().auto.foreach { x => // ...code using x... }
though the for-comprehension is usually more intuitive, and provides a more concise syntax
for situations where multiple resources are being managed at the same time. Direct use of
the methods foreach
and map
work well as pass-through operations, where a function
object instance is already available.
Generally this class is implemented by an implicit conversion which has ManagedResource[T]
in its return type signature rather than AutoResource[T]
, while the actual implementation
class actually is a subclass of AutoResource. This avoids an extra layer of allocation,
while hiding the foreach
, flatMap
, and map
methods which may not be desirable on
arbitrary types:
implicit def myResource[T <: MyType](r: T): ManagedResource[T] = new AutoResource[T](r) { override protected def close(value: T) { // use arg "value", not "r", below to avoid an extra class field for "r" value.myCloseMethod() } }
However, in some situations it may be more useful to have the returned AutoResource be defined by something else, such as a common trait or superclass which is not itself exposed to implicit conversion to ManagedResource. In that case, a value class implementation can be used to avoid the overhead of an extra layer of objects:
implicit class MyResource[T <: MyType](private val r: T) extends AnyVal with ManagedResource[T] { def auto: AutoResource[T] = new MyAutoResource[T](r) }
type of the contained resource
Separate conversion to isolate Java 7 AutoCloseable
support for classes that are not Closeable
.
The most common use case: a resource that implements java.io.Closeable
.
Implicit conversions based on existence of methods (duck typing).
Implicit conversions based on existence of methods (duck typing). These must be imported explicitly to avoid exposing conversions to ManagedResource unless that behavior is specifically desired.