Skip to content

Commit

Permalink
Merge pull request #179 from Kevin-Lee/task/170/add-Either.forEachLeft
Browse files Browse the repository at this point in the history
Close #170 - Add Either.forEachLeft
  • Loading branch information
kevin-lee committed Dec 31, 2021
2 parents eecdb7e + 2793b08 commit 4e8e1dc
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/main/java/j8plus/types/Either.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ public abstract <C> C fold(

public abstract void forEach(Consumer<? super B> f);

public abstract void forEachLeft(Consumer<? super A> f);

public abstract Optional<B> toOptional();

public Maybe<B> toMaybe() {
Expand Down Expand Up @@ -151,6 +153,11 @@ public A getLeftOrElse(final Supplier<A> alternative) {
public void forEach(final Consumer<? super B> f) {
}

@Override
public void forEachLeft(final Consumer<? super A> f) {
f.accept(this.value);
}

@Override
public Optional<B> toOptional() {
return Optional.empty();
Expand Down Expand Up @@ -249,6 +256,10 @@ public void forEach(final Consumer<? super B> f) {
f.accept(this.value);
}

@Override
public void forEachLeft(final Consumer<? super A> f) {
}

@Override
public Optional<B> toOptional() {
return Optional.ofNullable(value);
Expand Down
29 changes: 29 additions & 0 deletions src/test/java/j8plus/types/EitherTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,35 @@ public void forEach_RightCase() {
);
}

@Test
public void forEachLeft_LeftCase() {
final String input = "Some error";
final String expected = input;
final String[] updated = { null };
test("Either.forEachLeft on Left", "Either.forEachLeft on Left should apply the given function with side-effect")
.when(() ->
Either.<String, Integer>left(input)
.forEachLeft(err -> updated[0] = err)
)
.then(() ->
assertThat(updated[0]).isEqualTo(expected)
);
}

@Test
public void forEachLeft_RightCase() {
final Integer input = 999;
final String[] updated = { null };
test("Either.forEachLeft on Right", "Either.forEachLeft on Right should do nothing")
.when(() ->
Either.<String, Integer>right(input)
.forEachLeft(err -> updated[0] = err)
)
.then(() ->
assertThat(updated[0]).isNull()
);
}

@Test
public void toOptional_LeftCase() {
final String leftValue = "Some Error";
Expand Down

0 comments on commit 4e8e1dc

Please sign in to comment.