From 257f08c4c3c429d5e0853a3a2870f227f244d297 Mon Sep 17 00:00:00 2001 From: Joseph Cooper Date: Mon, 11 Oct 2021 17:37:39 +0100 Subject: [PATCH] Create new extension function rethrow along with tests for it --- .../com/github/michaelbull/result/Rethrow.kt | 11 +++++ .../github/michaelbull/result/RethrowTest.kt | 43 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Rethrow.kt create mode 100644 kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/RethrowTest.kt diff --git a/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Rethrow.kt b/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Rethrow.kt new file mode 100644 index 0000000..48a3bab --- /dev/null +++ b/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Rethrow.kt @@ -0,0 +1,11 @@ +package com.github.michaelbull.result + +/** + * If the [Result] is [Err] and contains a [Throwable], throws the [error][Err.error] + * if it is an instance of [E]. + * + * @throws E if [error][Err.error] is an instance of [E] + */ +public inline fun Result.rethrow() + : Result = + mapError { e -> if (e is E) throw e else e } diff --git a/kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/RethrowTest.kt b/kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/RethrowTest.kt new file mode 100644 index 0000000..6995ddb --- /dev/null +++ b/kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/RethrowTest.kt @@ -0,0 +1,43 @@ +package com.github.michaelbull.result + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class RethrowTest { + + @Test + fun throwsInstancesOfChosenThrowable() { + val result: Result = Err(RuntimeException()) + + assertFailsWith { + result.rethrow() + } + } + + @Test + fun nothingThrownIfWrappedExceptionIsNotInstance() { + val result: Result = Err(NullPointerException()) + + result.rethrow() + } + + @Test + fun nothingThrownIfErrorIsNull() { + val result: Result = Err(null) + + result.rethrow() + } + + @Test + fun doesntAlterOkValue() { + val result: Result = Ok("ok") + + assertEquals( + expected = "ok", + actual = result.rethrow().unwrap() + ) + } + +} +