Created
April 30, 2022 17:35
-
-
Save SecretX33/f282c03dc71519f9d9c402291d0397ff to your computer and use it in GitHub Desktop.
Proper Kotlin Closeable close function
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
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