Skip to content

Instantly share code, notes, and snippets.

@apatrida
Last active October 1, 2015 18:46
Show Gist options
  • Save apatrida/3222d5facd8959b0a4cb to your computer and use it in GitHub Desktop.
Save apatrida/3222d5facd8959b0a4cb to your computer and use it in GitHub Desktop.
How to make your own support for AutoCloseable
class Fred : AutoCloseable {
override fun close() {
}
}
public fun foo() {
Fred().use {
// do something then autoclose
}
}
public inline fun <T : AutoCloseable, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
close()
} catch (closeException: Exception) {
// eat the closeException as we are already throwing the original cause
// and we don't want to mask the real exception
}
throw e
} finally {
if (!closed) {
close()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment