Resources

Examples of using the Resource API to wrap existing Java IO objects

Perform Additional Action On Close

Perform additional actions when a resource is closed. One of the important features of the Scala IO is that resources are cleaned up automatically. However occasionally one would like to perform an action on close in addition to the default closing/flushing of the resource. When a resource is created additional close actions can be added and they will be executed just before the resource is closed.
    import scalax.io._
    import nio.SeekableFileChannel

    // a close action can be created by passing a function to execute
    // to the Closer object's apply method
    // '''WARNING''' When defining a CloseAction make its type as generic
    // as possible.  IE if it can be a CloseAction[Closeable] do not
    // make it a CloseAction[InputStream].  The reason has to do
    // with contravariance.  If you don't know what that means
    // don't worry just trust me ;-)
    val closer = CloseAction{(channel:Any) =>
      println("About to close "+channel)
    }

    // another option is the extend/implement the CloseAction trait
    val closer2 = new CloseAction[Any]{

      protected def closeImpl(a: Any):Unit =
        println("Message from second closer")
    }

    // closers can naturally be combined
    val closerThenCloser2 = closer +: closer2
    val closer2ThenCloser = closer :+ closer2

    // we can then create a resource and pass it to the closer parameter
    // now each time resource is used (and closed) the closer will also be executed
    // just before the actual closing.
    val resource = Resource.fromFileString("file")(closer)

    // closeActions can also be added to an existing resource
    // NOTE: Appended actions still are performed BEFORE
    // resource is closed
    resource.appendCloseAction(closerThenCloser2)
    resource.prependCloseAction(closer2)

    // The following are equivalent
    Resource.fromFileString("file")(closer :+ closer2)
    Resource.fromFileString("file")(closer).appendCloseAction(closer2)
    Resource.fromFileString("file").appendCloseAction (closer :+ closer2)