What Automatic Resource Management alternatives exist for Scala?

后端 未结 9 1393
半阙折子戏
半阙折子戏 2020-12-02 03:57

I have seen many examples of ARM (automatic resource management) on the web for Scala. It seems to be a rite-of-passage to write one, though most look pretty much like one a

9条回答
  •  囚心锁ツ
    2020-12-02 04:18

    Another alternative is Choppy's Lazy TryClose monad. It's pretty good with database connections:

    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
    }
    

    And with streams:

    val output = for {
      outputStream      <- TryClose(new ByteArrayOutputStream())
      gzipOutputStream  <- TryClose(new GZIPOutputStream(outputStream))
      _                 <- TryClose.wrap(gzipOutputStream.write(content))
    } yield wrap({gzipOutputStream.flush(); outputStream.toByteArray})
    
    output.resolve.unwrap match {
      case Success(bytes) => // process result
      case Failure(e) => // handle exception
    }
    

    More info here: https://github.com/choppythelumberjack/tryclose

提交回复
热议问题