Is there a more idiomatic way of opening a resource in Scala and applying methods to it than this method (translated directly from java):
var is: FileInputStream = null try { is = new FileInputStream(in) func(is) } catch { case e: IOException => println("Error: could not open file.") println(" -> " + e) exit(1) } finally { if(is) is.close() }
The main purpose of try functions is to catch errors/exceptions that are thrown by Dynamics NAV or exceptions that are thrown during . NET Framework interoperability operations. Try functions catch errors similar to a conditional Codeunit.
When dealing with errors in a purely functional way, we try as much as we can to avoid exceptions. Exceptions break referential transparency and lead to bugs when callers are unaware that they may happen until it's too late at runtime.
Try/catch blocks allow a program to handle an exception gracefully in the way the programmer wants them to. For example, try/catch blocks will let a program print an error message (rather than simply crash) if it can't find an input file. Try blocks are the first part of try/catch blocks.
The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result.
The loan pattern is implemented in various ways in Josh Suereth's scala-arm library on github.
You can then use a resource like this:
val result = managed(new FileInputStream(in)).map(func(_)).opt
which would return the result of func
wrapped in an Option
and take care of closing the input stream.
To deal with the possible exceptions when creating the resource, you can combine with the scala.util.control.Exception
object:
import resource._ import util.control.Exception.allCatch allCatch either { managed(new FileInputStream(in)).map(func(_)).opt } match { case Left(exception) => println(exception) case Right(Some(result)) => println(result) case _ => }
Use the Loan pattern (dead link) non permanent link to new location.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With