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

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

    Choppy's Lazy TryClose monad might be what you are looking for (disclosure: I'm the author). It is very similar to Scala's Try but automatically closes resources automatically.

    val ds = new JdbcDataSource()
    val output = for {
      conn  <- TryClose(ds.getConnection())
      ps    <- TryClose(conn.prepareStatement("select * from MyTable"))
      rs    <- TryClose.wrap(ps.executeQuery())
    } yield wrap(extractResult(rs))
    
    // Note that Nothing will actually be done until 'resolve' is called
    output.resolve match {
        case Success(result) => // Do something
        case Failure(e) =>      // Handle Stuff
    }
    

    See here for more info: https://github.com/choppythelumberjack/tryclose

提交回复
热议问题