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?


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.


Easy to fix:


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 {

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()



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