0

I have the following method that deals with multiple streams and I now want to add exception handling in a functional style. Any suggestions?

private def convertToByte(json: String): Array[Byte] = {

    val bytes= json.getBytes("UTF-8")
    val bin: ByteArrayInputStream = new ByteArrayInputStream(bytes)
    val bos: ByteArrayOutputStream = new ByteArrayOutputStream()
    val gzip: GZIPOutputStream = new GZIPOutputStream(bos)
    val buff = new Array[Byte](1024)
    var len = bin.read(buff)

    while(len != -1) 
    {
        gzip.write(buff, 0, len)
        len = bin.read(buff)
    }

    gzip.finish()
    bin.close()
    bos.close()
    gzip.close()
    bos.toByteArray
}

I want to wrap all the calls to close in a finally block and at the same time, in case of an exception, I want to catch that and return the error message as a byte array. Having worked with Java, my hand automatically goes the imperative way to wrap the piece of code in a try catch finally, but I'm thinking of writing it in a functional way by wrapping that in a higher order function. But I'm stuck getting started. Any pointers?

Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
joesan
  • 13,963
  • 27
  • 95
  • 232
  • possible duplicate of [How can I express \*finally\* equivalent for a Scala's Try?](http://stackoverflow.com/questions/20632250/how-can-i-express-finally-equivalent-for-a-scalas-try) – om-nom-nom Feb 25 '14 at 14:28
  • But I do not have Scala 2.10 and I'm not sure if the Try is available in Scala 2.9.1 that I currently use! – joesan Feb 25 '14 at 14:31
  • The other posts that you pointed declaresa var outside the try block and it is what I want to completely avoid. – joesan Feb 25 '14 at 14:39
  • 1
    Try is available in 2.9.3 which is binary compatible with 2.9.1 (so you could swap them without any problems); as for the vars -- [the answer with ARM usage](http://stackoverflow.com/a/5151093/298389) uses only vals and no Try – om-nom-nom Feb 25 '14 at 14:44

0 Answers0