diff --git a/lib/api/lib.api b/lib/api/lib.api index 57f2bd3..388ab99 100644 --- a/lib/api/lib.api +++ b/lib/api/lib.api @@ -240,6 +240,7 @@ public final class app/cash/quiver/extensions/OptionKt { public static final fun forEach (Larrow/core/Option;Lkotlin/jvm/functions/Function1;)V public static final fun ifAbsent (Larrow/core/Option;Lkotlin/jvm/functions/Function0;)V public static final fun or (Larrow/core/Option;Larrow/core/Option;)Larrow/core/Option; + public static final fun orEmpty (Larrow/core/Option;Lkotlin/jvm/functions/Function1;)Ljava/lang/String; public static final fun toValidatedNel (Larrow/core/Option;Lkotlin/jvm/functions/Function0;)Larrow/core/Validated; public static final fun unit (Larrow/core/Option;)Larrow/core/Option; } diff --git a/lib/src/main/kotlin/app/cash/quiver/extensions/Option.kt b/lib/src/main/kotlin/app/cash/quiver/extensions/Option.kt index fb278cf..ef0f5af 100644 --- a/lib/src/main/kotlin/app/cash/quiver/extensions/Option.kt +++ b/lib/src/main/kotlin/app/cash/quiver/extensions/Option.kt @@ -6,6 +6,7 @@ import arrow.core.None import arrow.core.Option import arrow.core.Some import arrow.core.ValidatedNel +import arrow.core.getOrElse import arrow.core.nonEmptyListOf /** @@ -41,3 +42,10 @@ infix fun Option.or(other: Option): Option = when (this) { is Some -> this is None -> other } + +/** + * Will return an empty string if the Optional value supplied is None + */ +fun Option.orEmpty(f: (T) -> String): String = this.map(f).getOrElse { "" } + + diff --git a/lib/src/test/kotlin/app/cash/quiver/extensions/OptionTest.kt b/lib/src/test/kotlin/app/cash/quiver/extensions/OptionTest.kt index e57d11e..f56a072 100644 --- a/lib/src/test/kotlin/app/cash/quiver/extensions/OptionTest.kt +++ b/lib/src/test/kotlin/app/cash/quiver/extensions/OptionTest.kt @@ -29,4 +29,12 @@ class OptionTest : StringSpec({ None.or(other) shouldBe other } } + + "orEmpty returns an empty string if used on a None" { + None.orEmpty { "I am an useless string " } shouldBe "" + } + + "orEmpty returns the string supplied if value is Some" { + "apples".some().orEmpty { "I wanna eat $it" } shouldBe "I wanna eat apples" + } })