Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add 'orEmpty' convenience function to Option #58

Merged
merged 1 commit into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/api/lib.api
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
8 changes: 8 additions & 0 deletions lib/src/main/kotlin/app/cash/quiver/extensions/Option.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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

/**
Expand Down Expand Up @@ -41,3 +42,10 @@ infix fun <T> Option<T>.or(other: Option<T>): Option<T> = when (this) {
is Some -> this
is None -> other
}

/**
* Will return an empty string if the Optional value supplied is None
*/
fun <T> Option<T>.orEmpty(f: (T) -> String): String = this.map(f).getOrElse { "" }


Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
})
Loading