[history] Copied bahaviour of AutoCloseable.use{} without dependency on interface

This commit is contained in:
Andrew Golovashevich 2025-02-24 02:15:53 +03:00
commit 15146e02aa

View File

@ -0,0 +1,23 @@
package ru.landgrafhomyak.utility.highlevel_try_finally
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
inline fun <R> safeAutoClose(onError: () -> Unit = {}, action: () -> R): R {
contract {
callsInPlace(action, InvocationKind.EXACTLY_ONCE)
callsInPlace(onError, InvocationKind.AT_MOST_ONCE)
}
val ret: R
try {
ret = action()
} catch (e1: Throwable) {
try {
onError()
} catch (e2: Throwable) {
e1.addSuppressed(e2)
}
throw e1
}
return ret
}