From bd951dfca2d07fee0cdbf847fc84638dd1229376 Mon Sep 17 00:00:00 2001 From: Jorge Castillo Date: Wed, 8 Jul 2020 12:22:56 +0200 Subject: [PATCH] Adds fromNullable to Either companion. --- arrow-core-data/src/main/kotlin/arrow/core/Either.kt | 2 ++ .../src/test/kotlin/arrow/core/EitherTest.kt | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/arrow-core-data/src/main/kotlin/arrow/core/Either.kt b/arrow-core-data/src/main/kotlin/arrow/core/Either.kt index cead99761..7431eee94 100644 --- a/arrow-core-data/src/main/kotlin/arrow/core/Either.kt +++ b/arrow-core-data/src/main/kotlin/arrow/core/Either.kt @@ -852,6 +852,8 @@ sealed class Either : EitherOf { fun right(right: R): Either = Right(right) + fun fromNullable(a: A?): Either = a?.right() ?: Unit.left() + tailrec fun tailRecM(a: A, f: (A) -> Kind, Either>): Either { val ev: Either> = f(a).fix() return when (ev) { diff --git a/arrow-core-data/src/test/kotlin/arrow/core/EitherTest.kt b/arrow-core-data/src/test/kotlin/arrow/core/EitherTest.kt index 15ea457fd..9cb557cb4 100644 --- a/arrow-core-data/src/test/kotlin/arrow/core/EitherTest.kt +++ b/arrow-core-data/src/test/kotlin/arrow/core/EitherTest.kt @@ -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() { @@ -73,6 +74,16 @@ class EitherTest : UnitSpec() { FxLaws.laws, 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() }