Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala finally block closing/flushing resource

Tags:

Is there a better way to ensure resources are properly released - a better way to write the following code ?

        val out: Option[FileOutputStream] = try {
          Option(new FileOutputStream(path))
        } catch {
          case _ => None
        }


        if (out.isDefined) {

          try {
            Iterator.continually(in.read).takeWhile(-1 != _).foreach(out.get.write)
          } catch {
            case e => println(e.getMessage)
          } finally {
            in.close
            out.get.flush()
            out.get.close()
          }

        }
like image 493
Dzhu Avatar asked Jan 14 '12 22:01

Dzhu


2 Answers

Something like that is a good idea, but I'd make it a method:

def cleanly[A,B](resource: => A)(cleanup: A => Unit)(code: A => B): Option[B] = {
  try {
    val r = resource
    try { Some(code(r)) }
    finally { cleanup(r) }
  } catch {
    case e: Exception => None
  }
}

(note that we only catch once; if you really want a message printed in one case and not the other, then you do have to catch both like you did). (Also note that I only catch exceptions; catching Error also is usually unwise, since it's almost impossible to recover from.) The method is used like so:

cleanly(new FileOutputStream(path))(_.close){ fos =>
  Iterator.continually(in.read).takeWhile(_ != -1).foreach(fos.write)
}

Since it returns a value, you'll get a Some(()) if it succeeded here (which you can ignore).


Edit: to make it more general, I'd really have it return an Either instead, so you get the exception. Like so:

def cleanly[A,B](resource: => A)(cleanup: A => Unit)(code: A => B): Either[Exception,B] = {
  try {
    val r = resource
    try { Right(code(r)) } finally { cleanup(r) }
  }
  catch { case e: Exception => Left(e) }
}

Now if you get a Right, all went okay. If you get a Left, you can pick out your exception. If you don't care about the exception, you can use .right.toOption to map it into an option, or just use .right.map or whatever to operate on the correct result only if it is there (just like with Option). (Pattern matching is a useful way to deal with Eithers.)

like image 54
Rex Kerr Avatar answered Oct 07 '22 07:10

Rex Kerr


Have a look at Scala-ARM

This project aims to be the Scala Incubator project for Automatic-Resource-Management in the scala library ...

... The Scala ARM library allows users to ensure opening closing of resources within blocks of code using the "managed" method. The "managed" method essentially takes an argument of "anything that has a close or dispose method" and constructs a new ManagedResource object.

like image 21
Derek Wyatt Avatar answered Oct 07 '22 07:10

Derek Wyatt