Move more logic of 'use' into 'closeSuppressed', rename the latter to 'closeFinally', that will result in more compact inline call expansions.

This commit is contained in:
Ilya Gorbunov
2017-01-09 23:35:46 +03:00
parent a71b68268d
commit 35d433160e
5 changed files with 36 additions and 29 deletions
@@ -19,7 +19,7 @@ internal open class PlatformImplementations {
@SinceKotlin("1.1")
@PublishedApi
@Deprecated("Provided for binary compatibility", level = DeprecationLevel.HIDDEN)
internal fun platformCloseSuppressed(instance: Closeable, cause: Throwable) = instance.closeSuppressed(cause)
internal fun platformCloseSuppressed(instance: Closeable, cause: Throwable) = instance.closeFinally(cause)
@JvmField
+18 -13
View File
@@ -30,27 +30,32 @@ import kotlin.internal.*
*/
@InlineOnly
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var closed = false
var exception: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
closed = true
this?.closeSuppressed(e)
exception = e
throw e
} finally {
if (this != null && !closed) {
close()
}
this.closeFinally(exception)
}
}
/**
* Closes this [Closeable], suppressing possible exception or error thrown by [Closeable.close] function when
* it's being closed due to some other [cause] exception occurred.
*
* The suppressed exception is added to the list of suppressed exceptions of [cause] exception, when it's supported.
*/
@SinceKotlin("1.1")
@PublishedApi
internal fun Closeable.closeSuppressed(cause: Throwable) {
try {
close()
} catch (closeException: Throwable) {
// on Java 7 we should call
IMPLEMENTATIONS.addSuppressed(cause, closeException)
}
internal fun Closeable?.closeFinally(cause: Throwable?) = when {
this == null -> {}
cause == null -> close()
else ->
try {
close()
} catch (closeException: Throwable) {
cause.addSuppressed(closeException)
}
}