Simple file read with Scala ARM library

scala

Solution

I find it weird too that `map` and `flatMap` should behave in a slightly different way. Maybe the mapping operation gives more freedom to expose a simplified result that can't be obtained through flatMap.

Anyway you could structure the code as follows to get something that looks more appealing

def readResource(resourceName: String): Option[String] = {
  val managedWriter = {
      managed(new StringWriter) and
      managed(this.getClass.getClassLoader.getResourceAsStream(resourceName))
    } map { case (writer, is) => 
        IOUtils.copy(is, writer)
        writer.toString
    }
  }
  managedWriter.opt
}

warn: the code is not tested

Problem

I am using the ARM library to read a resource file into a string. The code I'm using is this: ``` def readResource(reosurceName: String): String = { val res = for (writer <- managed(new StringWriter); is <- managed(this.getClass.getClassLoader.getResourceAsStream(resourceName))) yield { IOUtils.copy(is, writer) writer.toString } res.acquireAndGet(identity) } ``` It looks a bit weird to me, especially the last part with `acquireAndGet` of `identity`. Is there a better way ? The general question would be, how would you use this style to do something like this ``` val x: String= for (res1 <- managed(...); res2 <- managed(...); ... resn <- managed) yield { f(res1, res2, ..., resn) } ``` The behavior is that if the operations within the for comprehension fail I would like the exception to be propagated out of the method and the resources should be closed. I saw that map on a `ManagedResource` returns an `ExtractableManagedResource` from which I can extract the result using the `opt` method. `flatMap` returns only a `ManagedResource`. Is there a reason for this ?

Original source