在scala中释放IO资源而不保持可变状态

时间:2013-02-10 01:17:11

标签: scala immutability resource-management

我需要使用一些Java库,它可能会在一个方法中抛出一些异常,并在另一组方法中返回错误代码。到目前为止,它导致像

这样丑陋的代码
val txn = mgr.prepareTransaction()
val accessRecord = txn.readByQuery(...)
var state : Either[MyError, Result] = null //
try {
  // do something here
  val result = txn.runCodeWithin(new Callable[Result]() {...})
  if (result == -1) {
    state = Left(CanNotReadRecord)
  } else {
    state = Right(txn.getCachedRecord())
  }
} catch {
  case e: Exception => state = Left(GeneralError(e))
} finally {
  state match {
    case Right(_) => txn.commit();
    case _        => txn.rollback();
  }
}

我最感兴趣的是将状态删除为 var 以及检查finally块中的状态的能力。请指教。

2 个答案:

答案 0 :(得分:4)

Scala 2.10引入了Try类,它是Either[Throwable, Result]用例的更多功能替代。它拥有所有常用的monad操作(使得理解能够起作用的东西),以及一些其他有用的方法。 (check out the docs for Try here

以下是使用Try重新实现代码的可能性,并将CanNotReadRecord替换为CanNotReadRecordException。它应该在功能上等同于您的示例,但替换除外。

def txResults(txn: Transaction): Try[Record] = for {
    result <- Try{ txn.runCodeWithin(...) }
    checked <- result match {
        case -1 => Failure( new CanNotReadRecordException )
        case _ => Success( txn.getCachedRecord )
    }
} yield checked

txResults(txn) match {
    case Success(record) => txn.commit()
    case Failure(e) => txn.rollback() //and maybe handle `e`
}

答案 1 :(得分:3)

Scala ARM(自动资源管理)库以优雅的气密方式处理所有这类事情。

检查出来。