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)
}
}
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.
AutoClosable
out-of-the-box is that they are still to implement Java8 support, as well to support JDK8 classes – Conscienceuse
and changeCloseable
toAutoCloseable
(see ReadWrite.kt:145-177. – Anguish