java try-with-resource not working with scala

后端 未结 3 1695
-上瘾入骨i
-上瘾入骨i 2021-02-05 11:44

In Scala application, am trying to read lines from a file using java nio try-with-resource construct.

Scala version 2.11.8
Java version 1.8

try(Strea         


        
3条回答
  •  心在旅途
    2021-02-05 11:58

    You have the already mentioned in one of the answers approach:

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

    But I think the following is much more elegant:

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

    With the last one IMHO it's easier to handle the control flow.

提交回复
热议问题