Skip to content
This repository has been archived by the owner on Feb 24, 2021. It is now read-only.

Adds Either.fromNullable #181

Merged
merged 3 commits into from
Jul 8, 2020
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
2 changes: 2 additions & 0 deletions arrow-core-data/src/main/kotlin/arrow/core/Either.kt
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,8 @@ sealed class Either<out A, out B> : EitherOf<A, B> {

fun <R> right(right: R): Either<Nothing, R> = Right(right)

fun <A> fromNullable(a: A?): Either<Unit, A> = a?.right() ?: Unit.left()

tailrec fun <L, A, B> tailRecM(a: A, f: (A) -> Kind<EitherPartialOf<L>, Either<A, B>>): Either<L, B> {
val ev: Either<L, Either<A, B>> = f(a).fix()
return when (ev) {
Expand Down
11 changes: 11 additions & 0 deletions arrow-core-data/src/test/kotlin/arrow/core/EitherTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import arrow.core.test.laws.TraverseLaws
import arrow.typeclasses.Eq
import io.kotlintest.properties.Gen
import io.kotlintest.properties.forAll
import io.kotlintest.shouldBe

class EitherTest : UnitSpec() {

Expand Down Expand Up @@ -73,6 +74,16 @@ class EitherTest : UnitSpec() {
FxLaws.laws<EitherPartialOf<String>, Int>(Gen.int().map(::Right), GEN.map { it }, Either.eqK(String.eq()).liftEq(Int.eq()), ::either, ::either)
)

"fromNullable should lift value as a Right if it is not null" {
forAll { a: Int ->
Either.fromNullable(a) == Right(a)
}
}

"fromNullable should lift value as a Left(Unit) if it is null" {
Either.fromNullable(null) shouldBe Left(Unit)
}

"empty should return a Right of the empty of the inner type" {
forAll { _: String ->
Right(String.monoid().run { empty() }) == Either.monoid(String.monoid(), String.monoid()).run { empty() }
Expand Down