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

Commit

Permalink
Adds fromNullable to Either companion. (#181)
Browse files Browse the repository at this point in the history
Co-authored-by: Alberto Ballano <aballano@users.noreply.github.com>
  • Loading branch information
JorgeCastilloPrz and aballano authored Jul 8, 2020
1 parent d30f5e2 commit 4123e5f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
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

0 comments on commit 4123e5f

Please sign in to comment.