In Scala application, am trying to read lines from a file using java nio try-with-resource construct.
Scala version 2.11.8
Java version 1.8
try(Strea
You have the already mentioned in one of the answers approach:
def autoClose[A <: AutoCloseable, B](resource: A)(code: A ⇒ B): B = {
try
code(resource)
finally
resource.close()
}
But I think the following is much more elegant:
def autoClose[A <: AutoCloseable, B](resource: A)(code: A ⇒ B): Try[B] = {
val tryResult = Try {code(resource)}
resource.close()
tryResult
}
With the last one IMHO it's easier to handle the control flow.