From 09d341ae6dc5222a15430e10adae5bcebd64f436 Mon Sep 17 00:00:00 2001 From: Michael Bull Date: Wed, 26 Aug 2020 17:22:55 +0100 Subject: [PATCH] Add Scala's merge https://www.scala-lang.org/api/2.12.0/scala/util/Either$$MergeableEither.html#merge:A --- .../com/github/michaelbull/result/Get.kt | 13 +++++++++++++ .../com/github/michaelbull/result/GetTest.kt | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Get.kt b/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Get.kt index 04a2a69..7034f5d 100644 --- a/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Get.kt +++ b/kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Get.kt @@ -120,3 +120,16 @@ inline infix fun Result.getErrorOrElse(transform: (V) -> E): E { is Err -> error } } + +/** + * Merges this [Result][Result] to [U], returning the [value][Ok.value] if this [Result] is [Ok], otherwise the + * [error][Err.error]. + * + * - Scala: [MergeableEither.merge](https://www.scala-lang.org/api/2.12.0/scala/util/Either$$MergeableEither.html#merge:A) + */ +fun Result.merge(): U { + return when (this) { + is Ok -> value + is Err -> error + } +} diff --git a/kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/GetTest.kt b/kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/GetTest.kt index 945de6c..510e2b9 100644 --- a/kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/GetTest.kt +++ b/kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/GetTest.kt @@ -106,4 +106,22 @@ class GetTest { ) } } + + class Merge { + @Test + fun returnsValueIfOk() { + assertEquals( + expected = listOf(1, 2, 3), + actual = Ok(listOf(1, 2, 3)).merge() + ) + } + + @Test + fun returnsErrorIfErr() { + assertEquals( + expected = setOf(4, 5, 6), + actual = Err(setOf(4, 5, 6)).merge() + ) + } + } }