Package

scalaz

managed

Permalink

package managed

Visibility
  1. Public
  2. All

Type Members

  1. sealed abstract class Managed[A] extends AnyRef

    Permalink

    An example Scala program to copy data from one handle to another might look like this:

    An example Scala program to copy data from one handle to another might look like this:

    def main(args: Array[String]) =
      withFileInputStream("inFile.txt")(is =>
        withFileOutputStream("outFile.txt")(os =>
          copy(is, os)
        )
      )
    
    // A hypothetical function for safely using a FileInputStream
    def withFileInputStream[A](path: String)(f: FileInputStream => IO[A]): IO[A]
    
    // A hypothetical function for safely using a FileOutputStream
    def withFileOutputStream[A](path: String)(f: FileOutputStream => IO[A]): IO[A]
    
    // A hypothetical function that copies data from an InputStream to an OutputStream
    def copy(is: InputStream, os: OutputStream): IO[Unit]

    withFileInputStream and withFileOutputStream are a few of many functions that acquire some resource in an exception-safe way. These functions take a callback function as an argument and they invoke the callback on the resource when it becomes available, guaranteeing that the resource is properly disposed if the callback throws an exception. These functions usually have a type that ends with the following pattern:

                          Callback
                        -------------
    def withXXX[A](...)(f: R => IO[A]): IO[A]

    Here are some examples other examples of this pattern:

    def withSocket[A](addr: SocketAddress)(f: Socket => IO[A]): IO[A]
    def withDB[A](config: DBConfig)(f: DB => IO[A]): IO[A]

    Acquiring multiple resources in this way requires nesting callbacks. However, you can wrap anything of the form A => IO[R] => IO[R] in the Managed monad, which translates binds to callbacks for you:

    import scalaz.managed._
    
    def fileInputStream(path: String): Managed[FileInputStream] =
      Managed(new Forall[Lambda[A => (FileInputStream => IO[A]) => IO[A]]] {
        def apply[A] = withFileInputStream(path)
      }
    
    def fileOutputStream(path: String): Managed[FileOutputStream] =
      Managed(new Forall[Lambda[A => (FileOutputStream => IO[A]) => IO[A]]] {
        def apply[A] = withFileOutputStream(path)
      }
    
     def main(args: Array[String]) =
       Managed.run(
         for {
           in  <- fileInputStream("inFile.txt")
           out <- fileOutputStream("outFile.txt")
           _   <- copy(in, out).liftIO[Managed]
         } yield ()
       )

Value Members

  1. object Examples extends SafeApp

    Permalink
  2. object Managed

    Permalink

Ungrouped