From 3810567b6c4ca8639c5c4374ceae68bc424a5fa7 Mon Sep 17 00:00:00 2001 From: Joseph Cooper Date: Tue, 26 Oct 2021 15:28:33 +0100 Subject: [PATCH] Added contracts to throwIf and throwUnless --- .../result/coroutines/RunSuspendCatching.kt | 4 ++++ .../result/coroutines/RunSuspendCatchingTest.kt | 11 +++++++++++ .../com/github/michaelbull/result/ThrowIfUnless.kt | 9 +++++++-- 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 kotlin-result-coroutines/src/commonMain/kotlin/com/github/michaelbull/result/coroutines/RunSuspendCatching.kt create mode 100644 kotlin-result-coroutines/src/jvmTest/kotlin/com/github/michaelbull/result/coroutines/RunSuspendCatchingTest.kt diff --git a/kotlin-result-coroutines/src/commonMain/kotlin/com/github/michaelbull/result/coroutines/RunSuspendCatching.kt b/kotlin-result-coroutines/src/commonMain/kotlin/com/github/michaelbull/result/coroutines/RunSuspendCatching.kt new file mode 100644 index 0000000..c63151e --- /dev/null +++ b/kotlin-result-coroutines/src/commonMain/kotlin/com/github/michaelbull/result/coroutines/RunSuspendCatching.kt @@ -0,0 +1,4 @@ +package com.github.michaelbull.result.coroutines + +class RunSuspendCatching { +} diff --git a/kotlin-result-coroutines/src/jvmTest/kotlin/com/github/michaelbull/result/coroutines/RunSuspendCatchingTest.kt b/kotlin-result-coroutines/src/jvmTest/kotlin/com/github/michaelbull/result/coroutines/RunSuspendCatchingTest.kt new file mode 100644 index 0000000..b244ad6 --- /dev/null +++ b/kotlin-result-coroutines/src/jvmTest/kotlin/com/github/michaelbull/result/coroutines/RunSuspendCatchingTest.kt @@ -0,0 +1,11 @@ +package com.github.michaelbull.result.coroutines + +import kotlin.test.Test + +class RunSuspendCatchingTest { + + @Test + fun propogatesCoroutineCancellation() { + val testDispatcher = TestCoroutineDispatcher() + } +} diff --git a/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/ThrowIfUnless.kt b/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/ThrowIfUnless.kt index ad93c40..087e6ad 100644 --- a/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/ThrowIfUnless.kt +++ b/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/ThrowIfUnless.kt @@ -1,5 +1,8 @@ package com.github.michaelbull.result +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract + /** * If the [Result] is [Err] and contains a [Throwable], throws the [error][Err.error] * if the [predicate] returns true. @@ -8,8 +11,10 @@ package com.github.michaelbull.result */ public inline fun Result.throwIf( predicate: (E) -> Boolean -): Result = - onFailure { e -> if (predicate(e)) throw e } +): Result { + contract { callsInPlace(predicate, InvocationKind.AT_MOST_ONCE) } + return onFailure { e -> if (predicate(e)) throw e } +} /** * If the [Result] is [Err] and contains a [Throwable], throws the [error][Err.error]