[history] Copied bahaviour of AutoCloseable.use{} without dependency on interface
This commit is contained in:
commit
15146e02aa
@ -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
|
||||
}
|
Loading…
Reference in New Issue
Block a user