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

后端 未结 7 1833
别那么骄傲
别那么骄傲 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:17

    this one works for me really well:

      implicit class ManagedCloseable[C <: AutoCloseable](resource: C) {
        def apply[T](block: (C) => T): T = {
        try {
          block(resource)
        } finally {
          resource.close()
        }
      }
    

    using it for example in this Apache Cassandra client code:

    val metadata = Cluster.builder().addContactPoint("vader").withPort(1234).build() { cluster =>
      cluster.getMetadata
    }
    

    or even shorter:

    val metadata = Cluster.builder().addContactPoint("sedev01").withPort(9999).build()(_.getMetadata)
    

提交回复
热议问题