From 5d5195af9deddf0bfd131aa3e0ad38766ce5544d Mon Sep 17 00:00:00 2001 From: Michael Bull Date: Wed, 22 Nov 2017 23:25:11 +0000 Subject: [PATCH] Add getErrorOrElse Matches getOrElse signature with respect to the error. --- src/main/kotlin/com/github/michaelbull/result/Get.kt | 11 +++++++++++ .../kotlin/com/github/michaelbull/result/GetTest.kt | 12 ++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/main/kotlin/com/github/michaelbull/result/Get.kt b/src/main/kotlin/com/github/michaelbull/result/Get.kt index d4e13ee..5478cdf 100644 --- a/src/main/kotlin/com/github/michaelbull/result/Get.kt +++ b/src/main/kotlin/com/github/michaelbull/result/Get.kt @@ -66,3 +66,14 @@ infix inline fun Result.getOrElse(transform: (E) -> V): V { is Err -> transform(error) } } + +/** + * @param transform The transformation to apply to the [value][Ok.value]. + * @return The [error][Err.error] if [Err], otherwise the [transformed][transform] [value][Ok.value]. + */ +infix inline fun Result.getErrorOrElse(transform: (V) -> E): E { + return when (this) { + is Ok -> transform(value) + is Err -> error + } +} diff --git a/src/test/kotlin/com/github/michaelbull/result/GetTest.kt b/src/test/kotlin/com/github/michaelbull/result/GetTest.kt index 2bf509e..0d89150 100644 --- a/src/test/kotlin/com/github/michaelbull/result/GetTest.kt +++ b/src/test/kotlin/com/github/michaelbull/result/GetTest.kt @@ -64,4 +64,16 @@ internal class GetTest { val value = Err("hello").getOrElse { "world" } assertThat(value, equalTo("world")) } + + @Test + internal fun `getErrorOrElse should return the transformed result value if ok`() { + val error = Ok("hello").getErrorOrElse { "world" } + assertThat(error, equalTo("world")) + } + + @Test + internal fun `getErrorOrElse should return the result error if not ok`() { + val error = Err("hello").getErrorOrElse { "world" } + assertThat(error, equalTo("hello")) + } }