Skip to content

Commit

Permalink
Merge pull request #64 from Kevin-Lee/task/61/add-from-maybe
Browse files Browse the repository at this point in the history
Close #61 - Add fromMaybe to Either
  • Loading branch information
kevin-lee committed Nov 15, 2019
2 parents f57a224 + 628b1d6 commit 9887a15
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/main/java/j8plus/types/Either.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ public static <A, B> Either<A, B> fromOptional(
}
}

public static <A, B> Either<A, B> fromMaybe(
final Maybe<? extends B> maybe
, final Supplier<? extends A> ifNone
) {
return maybe.fold(Either::right, () -> Either.left(ifNone.get()));
}

static final class Left<A, B> extends Either<A, B> {
final A value;

Expand Down
26 changes: 26 additions & 0 deletions src/test/java/j8plus/types/EitherTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,32 @@ public void fromOptional_EmptyCase() {
);
}

@Test
public void fromMaybe_JustCase() {
final Integer expectedValue = 999;
final Maybe<Integer> input = Maybe.just(expectedValue);
test("Either.fromMaybe(just)", "Either.fromMaybe(Just(someValue)) should create Right")
.when(() ->
Either.fromMaybe(input, () -> "Some error")
)
.then(actual ->
assertThat(actual).isEqualTo(Either.right(expectedValue))
);
}

@Test
public void fromMaybe_NothingCase() {
final String expectedValue = "Some error";
final Maybe<Integer> input = Maybe.nothing();
test("Either.fromMaybe(Nothing)", "Either.fromMaybe(Nothing) should create Left")
.when(() ->
Either.fromMaybe(input, () -> expectedValue)
)
.then(actual ->
assertThat(actual).isEqualTo(Either.left(expectedValue))
);
}

@Test
public void isLeft_LeftCase() {
test("Either.isLeft", "Either.isLeft should return true for Left")
Expand Down

0 comments on commit 9887a15

Please sign in to comment.