Resources

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

Why Are Close Actions Contravariant

This example examines why a CloseAction[Any] can be assigned to a CloseAction[String] but not vice-versa.

Normally one think in terms of ''Covariance'' (List[String] can be assigned to a List[Any]) but that cannot work for CloseActions so CloseActions have the exact opposite characteristics.

    import scalax.io._
    import java.io._

    // Since CloseAction is Defined as CloseAction[-A], the following compiles
    val action:CloseAction[String] = CloseAction[Any]{_ => ()}

    //But
    // val action:CloseAction[Any] = CloseAction[String]{_ => ()}
    // does not.

    // If you want to know why consider the following:
    val resource:Resource[InputStream] = Resource.fromInputStream(new FileInputStream("file"))
    val resource2:Resource[Closeable] = resource

    val closeAction:CloseAction[InputStream] = CloseAction{in:InputStream => println(in.available)}

    //Given the previous declarations it should be obvious that the following works
    val updatedResource:Resource[InputStream] = resource.appendCloseAction(closeAction)

    // However since resource2 is a Resource[Closeable] it should be obvious that one cannot
    // add a closeAction that requires an InputStream.  so the following would fail to compile
    // resource2.appendCloseAction(closeAction)