Functional try & catch with Scala

后端 未结 4 1517
傲寒
傲寒 2020-12-05 02:44

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: FileInputSt         


        
相关标签:
4条回答
  • 2020-12-05 03:23

    Use the Loan pattern (dead link) non permanent link to new location.

    0 讨论(0)
  • 2020-12-05 03:28

    That might be one case where it is not desirable to go functional. The allready mentioned loan pattern is only an encapsulation of the imparative version of error handling, but that has nothing to do with functional programming, and also doenst take care of error handling.

    If you really wanted it functional you could do it with an error handling monad. For good reasons the link I provide is Haskell specific documentation to this, as Scala is not supporting this kind of "hardcore" functional practice so well.

    I would reccomend to you to go the imperative way and use try catch finally... you could also extend the loan pattern with error handling but that means you have to either write special functions if you want to treat errors differently in some situations or you would have to pass over an partial function for error handling (which is nothing else than what you allready got inside the catch block in your code).

    0 讨论(0)
  • 2020-12-05 03:32

    Starting Scala 2.13, the standard library provides a dedicated resource management utility: Using.

    It can be used in this case with FileInputStream as it implements AutoCloseable in order to play with an input file and, no matter what, close the file resource afterwards:

    import scala.util.{Using, Failure}
    import java.io.FileInputStream
    
    Using(new FileInputStream(in)) {
      is => func(is)
    }.recoverWith {
      case e: java.io.IOException =>
        println("Error: could not open file.")
        Failure(e)
    }
    

    Since Using produces a Try providing either the result of the operation or an error, we can work with the exception via Try#recoverWith.

    0 讨论(0)
  • 2020-12-05 03:44

    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 _ =>
    }
    
    0 讨论(0)
提交回复
热议问题