Functional try & catch with Scala

后端 未结 4 1534
傲寒
傲寒 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: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.

提交回复
热议问题