Skip to content

Commit

Permalink
Add 'orEmpty' convenience function to Option (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
millyrowboat authored Sep 20, 2023
1 parent e728c39 commit a65ef0d
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
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 { "" }


8 changes: 8 additions & 0 deletions lib/src/test/kotlin/app/cash/quiver/extensions/OptionTest.kt
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"
}
})

0 comments on commit a65ef0d

Please sign in to comment.