Skip to content

Instantly share code, notes, and snippets.

@SecretX33
Created April 30, 2022 17:35
Show Gist options
  • Save SecretX33/f282c03dc71519f9d9c402291d0397ff to your computer and use it in GitHub Desktop.
Save SecretX33/f282c03dc71519f9d9c402291d0397ff to your computer and use it in GitHub Desktop.
Proper Kotlin Closeable close function
inline fun <T> Closeable.use(block: () -> T): T {
var exception: Throwable? = null
try {
return block()
} catch (e: Throwable) {
exception = e
throw e
} finally {
when (exception) {
null -> close()
else -> try {
close()
} catch (e: Throwable) {
exception.addSuppressed(e)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment