Last active
October 1, 2015 18:46
-
-
Save apatrida/3222d5facd8959b0a4cb to your computer and use it in GitHub Desktop.
How to make your own support for AutoCloseable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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