When I tried to write an equivalent of try-with-resources code in Kotlin it didn't work for me.
I tried different variations of the following:
try (writer = OutputStreamWriter(r.getOutputStream())) {
// ...
}
But neither works.
Does anyone know what should be used instead? Apparently Kotlin grammar doesn't have definition for such a construct, but may be I'm missing something. It defines grammar for try block as follows:
try : "try" block catchBlock* finallyBlock?;
There is
use
-function in kotlin stdlib (src).How to use it:
TL;DR
No special syntax, but
use
functionKotlin, as opposed to Java, does not have a special syntax for this. Instead, try-with-resources, is offered as the standard library function
use
.The
use
implementationThis function is defined as a generic extension on all
Closeable?
types.Closeable
is Java's interface that allows try-with-resources as of Java SE7.The function takes a function literal
block
which gets executed in atry
. Same as with try-with-resources in Java, theCloseable
gets closed in afinally
.Also failures happening inside
block
lead toclose
executions, where possible exceptions are literally "suppressed" by just ignoring them. This is different from try-with-resources, because such exceptions can be requested in Java‘s solution.How to use it
The
use
extension is available on anyCloseable
type, i.e. streams, readers and so on.The part in curly brackets is what becomes
block
inuse
(a lambda is passed as an argument here). After the block is done, you can be sure thatFileInputStream
has been closed.Edit: The following response is still valid for Kotlin 1.0.x. For Kotlin 1.1, there is support a standard library that targets java 8 to support closable resource pattern.
For other classes that do not support the "use" function, I have done the following homemade try-with-resources:
Then you can use it the following way: