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

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

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

7条回答
  •  Happy的楠姐
    2020-12-06 01:11

    This is the code I use:

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

    Unlike Java try-with-resources, the resource doesn't need to implement AutoCloseable. Only a close() method is needed. It only supports one resource.

    Here is an example use with an InputStream:

    val path = Paths get "/etc/myfile"
    use(Files.newInputStream(path)) { inputStream ⇒
        val firstByte = inputStream.read()
        ....
    }
    

提交回复
热议问题