Simple Scala pattern for “using/try-with-resources” (Automatic Resource Management)

后端 未结 7 1832
别那么骄傲
别那么骄傲 2020-12-06 00:37

C# has using with the IDisposable interface. Java 7+ has identical functionality with try and the AutoCloseable interface

7条回答
  •  被撕碎了的回忆
    2020-12-06 01:21

    An improvement I can recommend to the approach you suggested, which is:

      def autoClose[A <: AutoCloseable, B](resource: A)(code: A ⇒ B): B = {
        try
          code(resource)
        finally
          resource.close()
      }
    

    Is to use:

      def autoClose[A <: AutoCloseable, B](resource: A)(code: A ⇒ B): Try[B] = {
        val tryResult = Try {code(resource)}
        resource.close()
        tryResult
      }
    

    IMHO having the tryResult which is an Try[B], will allow you an easier control flow later.

提交回复
热议问题