try-with-resources: “use” extension function in Kotlin does not always work

后端 未结 4 1451
抹茶落季
抹茶落季 2021-01-11 10:51

I had some trouble expressing the Java\'s try-with-resources construct in Kotlin. In my understanding, every expression that is an instance of AutoClosable shou

4条回答
  •  孤城傲影
    2021-01-11 11:23

    Kotlin targets Java 6 at the moment, so its standard library does not use the AutoCloseable interface. The use function only supports the Java 6 Closeable interface. See the issue tracker for reference.

    You can create a copy of the use function in your project and modify it to replace Closeable with AutoCloseable:

    public inline fun  T.use(block: (T) -> R): R {
        var closed = false
        try {
            return block(this)
        } catch (e: Exception) {
            closed = true
            try {
                close()
            } catch (closeException: Exception) {
                e.addSuppressed(closeException)
            }
            throw e
        } finally {
            if (!closed) {
                close()
            }
        }
    }
    

提交回复
热议问题