Using a variable in finally block

前端 未结 4 1093
忘掉有多难
忘掉有多难 2021-01-22 10:29

Here is code in Scala:

def write() = {
    try {
      val out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)))
      out.println(\"123\")
          


        
4条回答
  •  [愿得一人]
    2021-01-22 11:36

    This is what I use to manage closable resources passed to function returning and not retuning futures

      def withClosable[ T, C <: Closeable ]( closable: C )( f: C ⇒ T ) = try { f( closable ) } finally { IOUtils closeQuietly closable }
    
      def withFutureClosable[ T <: Future[Any], C <: Closeable ]( closable: C )( f: C ⇒ T ) = f( closable ) andThen {
    
            case _ => IOUtils closeQuietly closable
        } 
    }
    

    I use IOUtils from commons-io to simplify the call to actually close the resource. A simple try { closable.close() } catch { case _ => /* blah */ } would do

    Example usage:

    withClosable(new FileInpustream("f")) { stream => /* read the stream */ }

提交回复
热议问题