I want a Closeable resource to auto-close itself, but at same time I want to be able to handle any possible exception.
Consider the following piece of code.
val opcPackage: OPCPackage
URI.create(document.fileUrl).toURL().openStream().use {
    opcPackage = OPCPackage.open(it)  // it = InputStream!
}
In case of exception, the InputStream will auto-close itself thanks to the use block. However, the execution flow will be interrupted.
I still want to handle such exception and do something with my program (e.g. log, send a signal ecc...)
The following does not compile:
kotlin.runCatching {
    URI.create(document.fileUrl).toURL().openStream().use {
        opcPackage = OPCPackage.open(it)
    }
}.onFailure { 
    // e.g. log and exit
}
This one kind of defeats the whole purpose of use since I have to manually close the Closeable.
URI.create(document.fileUrl).toURL().openStream().use {
    try {
        opcPackage = OPCPackage.open(it)
    } catch (ex: Exception) {
        // ...
        it.close()
        return internalServerError()
    }
}
At this point, I might as well simply use
val inputStream = URI.create(document.fileUrl).toURL().openStream()
try {
    opcPackage = OPCPackage.open(inputStream)
    inputStream.close()
} catch (ex: Exception) {
    inputStream.close()
    return internalServerError()
}
but I'm trying to use kotlin features properly.
What's the best snippet for this use-case?
useyou’ve to close the resource manually?kotlin.runCatching?runCatchingvariant not compile? What error are you getting? It should compile.returnstatement in the middle of those expressions. A more idiomatic Kotlin approach would be to use expressions to initialize your variable instead