org.duh.resource

ManagedResource

trait ManagedResource[T] extends Any

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)
}
T

type of the contained resource

Linear Supertypes
Any
Known Subclasses
Ordering
  1. Alphabetic
  2. By inheritance
Inherited
  1. ManagedResource
  2. Any
  1. Hide All
  2. Show all
Learn more about member selection
Visibility
  1. Public
  2. All

Abstract Value Members

  1. abstract def auto: AutoResource[T]

  2. abstract def getClass(): Class[_]

    Definition Classes
    Any

Concrete Value Members

  1. final def !=(arg0: Any): Boolean

    Definition Classes
    Any
  2. final def ##(): Int

    Definition Classes
    Any
  3. final def ==(arg0: Any): Boolean

    Definition Classes
    Any
  4. final def asInstanceOf[T0]: T0

    Definition Classes
    Any
  5. def equals(arg0: Any): Boolean

    Definition Classes
    Any
  6. def hashCode(): Int

    Definition Classes
    Any
  7. final def isInstanceOf[T0]: Boolean

    Definition Classes
    Any
  8. def toString(): String

    Definition Classes
    Any

Inherited from Any

Ungrouped