[history] Added try-else behaviour
This commit is contained in:
parent
15146e02aa
commit
1b9bf5e49f
@ -3,21 +3,27 @@ package ru.landgrafhomyak.utility.highlevel_try_finally
|
||||
import kotlin.contracts.InvocationKind
|
||||
import kotlin.contracts.contract
|
||||
|
||||
inline fun <R> safeAutoClose(onError: () -> Unit = {}, action: () -> R): R {
|
||||
inline fun <R> safeAutoClose(onError: () -> Unit = {}, onSuccess: () -> Unit = {}, action: () -> R): R {
|
||||
contract {
|
||||
callsInPlace(action, InvocationKind.EXACTLY_ONCE)
|
||||
callsInPlace(onError, InvocationKind.AT_MOST_ONCE)
|
||||
callsInPlace(onSuccess, InvocationKind.EXACTLY_ONCE)
|
||||
}
|
||||
val ret: R
|
||||
var wasError = false
|
||||
try {
|
||||
ret = action()
|
||||
} catch (e1: Throwable) {
|
||||
wasError = true
|
||||
try {
|
||||
onError()
|
||||
} catch (e2: Throwable) {
|
||||
e1.addSuppressed(e2)
|
||||
}
|
||||
throw e1
|
||||
} finally {
|
||||
if (!wasError)
|
||||
onSuccess()
|
||||
}
|
||||
return ret
|
||||
}
|
Loading…
Reference in New Issue
Block a user