TL; DR
No special syntax, but use function
Unlike Java, Kotlin has no special syntax for this. Instead, try-with-resources is suggested as a standard use library function.
FileInputStream("filename").use { fis -> //or implicit 'it' //use stream here }
Implementation use
@InlineOnly public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R { var closed = false try { return block(this) } catch (e: Exception) { closed = true try { this?.close() } catch (closeException: Exception) { } throw e } finally { if (!closed) { this?.close() } } }
Closeable? this function defined as a common extension for all Closeable? types. Closeable is a Java interface that lets you try resources with Java SE7 .
The function accepts a functional literal block that is executed in try . As with try-with-resources in Java, Closeable closes in finally .
Also, crashes that occur inside the block are executed at close , where possible exceptions are literally "suppressed", simply ignoring them. This is different from try-with-resources because such exceptions may be thrown in a Java solution.
How to use it
The use extension is available for any type of Closeable , i.e. Closeable , readers, etc.
FileInputStream("filename").use {
The part in braces that becomes block in use (lambda is passed as an argument here). After the block is done, you can be sure that the FileInputStream been closed.
s1m0nw1 Oct 20 '17 at 6:40 2017-10-20 06:40
source share