我自己的解决Kotlin缺少资源尝试的解决方案 [英] My own solution for Kotlin's try-with-resources absence

查看:158
本文介绍了我自己的解决Kotlin缺少资源尝试的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin为Closeable对象提供了use函数,但似乎他们忘记了将AutoCloseable(例如DB准备好的语句)考虑为try-with-resources完整的Java等效项.

Kotlin provides the use function for Closeable objects, but it seems they forgot to consider AutoCloseable (e.g. DB prepared statements) for the try-with-resources full Java equivalent.

我已经实现了下一个自制"解决方案:

I've implemented the next "home-made" solution:

inline fun <T:AutoCloseable,R> trywr(closeable: T, block: (T) -> R): R {
    try {
        return block(closeable);
    } finally {
        closeable.close()
    }
}

然后您可以将其用于下一种方式:

Then you can use it the next way:

fun countEvents(sc: EventSearchCriteria?): Long {
    return trywr(connection.prepareStatement("SELECT COUNT(*) FROM event")) {
        var rs = it.executeQuery()
        rs.next()
        rs.getLong(1)
    }
}

我是Kotlin的新手,我想知道我是否在自己的解决方案中缺少一些重要的东西,而这些东西可能会给我带来生产环境中的问题/泄漏.

I'm new to Kotlin and I would like to know if I'm missing something important in my own solution that could give me problems/leakages in a production environment.

推荐答案

您的实现可以正常工作,但是与标准的try-with-resources实现不同.如果您希望它像Java中那样工作,则应执行以下操作:

Your implementation will work fine but it's different from a standard try-with-resources implementation. If you want it to work like in Java you should do something like that:

inline fun <T : AutoCloseable, R> trywr(closeable: T, block: (T) -> R): R {
  var currentThrowable: java.lang.Throwable? = null
  try {
    return block(closeable)
  } catch (throwable: Throwable) {
    currentThrowable = throwable as java.lang.Throwable
    throw throwable
  } finally {
    if (currentThrowable != null) {
      try {
        closeable.close()
      } catch (throwable: Throwable) {
        currentThrowable.addSuppressed(throwable)
      }
    } else {
      closeable.close()
    }
  }
}

更新:

mfulton26 在他的

As mfulton26 pointed out in his comment kotlin.Throwable doesn't contain addSuppressed(Throwable) method so we have to cast kotlin.Throwable to java.lang.Throwable to make the code work.

这篇关于我自己的解决Kotlin缺少资源尝试的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆