Skip to content

Commit

Permalink
Adding Try#toEither(Supplier)) and Either#filterOrElse
Browse files Browse the repository at this point in the history
  • Loading branch information
VassilisSoum committed Aug 22, 2024
1 parent 3702361 commit 976a41e
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Then, you can add the dependency to your project.
<dependency>
<groupId>com.github.VassilisSoum</groupId>
<artifactId>FunctionalUtils</artifactId>
<version>2.4.0</version>
<version>2.8.0</version>
</dependency>
```

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.soumakis</groupId>
<artifactId>FunctionalUtils</artifactId>
<version>2.4.0</version>
<version>2.8.0</version>
<packaging>jar</packaging>

<properties>
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/com/soumakis/control/Either.java
Original file line number Diff line number Diff line change
Expand Up @@ -363,4 +363,12 @@ default <A, B> Either<A, B> biFlatMap(Function<? super L, ? extends Either<A, B>
}
return rightFn.apply(getRight());
}

default <C> Either<C, R> filterOrElse(Function<? super R, Boolean> predicate,
Supplier<C> supplier) {
if (isRight() && predicate.apply(getRight())) {
return Either.right(getRight());
}
return Either.left(supplier.get());
}
}
4 changes: 4 additions & 0 deletions src/main/java/com/soumakis/control/Try.java
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ default Either<Throwable, T> toEither() {
return fold(Either::left, Either::right);
}

default <U> Either<U, T> toEither(Supplier<U> leftSupplier) {
return fold(__ -> Either.left(leftSupplier.get()), Either::right);
}

/**
* Applies a function to the value if this is a {@code Success}, or a different function if this
* is a {@code Failure}.
Expand Down
8 changes: 8 additions & 0 deletions src/test/java/com/soumakis/control/EitherTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,12 @@ void testBiFlatMapRight() {
assert (mapped.getRight() == 2);
}

@Test
void testFilterOrElse() {
Either<String, Integer> right = Either.right(42);
Either<String, Integer> filtered = right.filterOrElse(n -> n > 42, () -> "error");
assert (filtered.isLeft());
assert (filtered.getLeft().equals("error"));
}

}

0 comments on commit 976a41e

Please sign in to comment.