Try-with-resources or use()


#1

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?


#2

Provided link doesn't seem to be related.

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

myStream.use {
  val line = readLine()
}


#3

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

PS: I have corrected the link.


#4

Easy to fix:

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


#5

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.


#6

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


#7

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


#8

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


#9

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