Try-with-resources or use()

try-with-resources and the Kotlin subsitute use() were mentioned in an older discussion. The link to the use() functions leads to nowhere. So what is the Kotlin solution for try-with-resources today?

1 Like

Provided link doesn't seem to be related.

use() function is now extension, e.g.:

myStream.use {
  val line = readLine()
}

Thanks. Would be nice to see it in the docs.

PS: I have corrected the link.

1 Like

Easy to fix:

https://github.com/JetBrains/kotlin-web-site/pull/87

1 Like

use() function is now extension, e.g.:

myStream.use {
  val line = readLine()
}


This doesn’t appear to do what you think it does. If I control-click readLine here I’m taken to the global method that reads from stdin.

We had a discussion about this question two months ago, Andrey said there are no plans to support the try-with-resources.

Andrey said about try-with-resources as a dedicated language feature. use() standard library function have been available for a long time.

What about?
package info.macias.kotlin

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

Example of use:

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

Gist: https://gist.github.com/mariomac/e81477965fbe03a9dd8a

In version 1.0, Kotlin does not support standard library multitargeting, so the standard library can only refer to classes that exist in Java 6. That’s the reason why we don’t include a version of use() that references AutoCloseable in the standard library. You’re, of course, welcome to use your variant of the function in your own code.

Support for standard library multitargeting is on the roadmap for Kotlin 1.1. For AutoCloseable support specifically, you’re welcome to watch and vote for https://youtrack.jetbrains.com/issue/KT-5899

2 Likes