File tree Expand file tree Collapse file tree 2 files changed +35
-1
lines changed
main/java/io/vavr/control
test/java/io/vavr/control Expand file tree Collapse file tree 2 files changed +35
-1
lines changed Original file line number Diff line number Diff line change 2828import java .util .NoSuchElementException ;
2929import java .util .Objects ;
3030import java .util .concurrent .Callable ;
31- import java .util .function .*;
31+ import java .util .function .Consumer ;
32+ import java .util .function .Function ;
33+ import java .util .function .Predicate ;
34+ import java .util .function .Supplier ;
3235
3336import static io .vavr .API .Match ;
3437import static io .vavr .control .TryModule .isFatal ;
@@ -131,6 +134,19 @@ public static <T> Try<T> ofCallable(Callable<? extends T> callable) {
131134 return of (callable ::call );
132135 }
133136
137+ /**
138+ * Creates a Try of an Either.
139+ *
140+ * @param either Either which left type is a {@link Throwable}
141+ * @param <E> The type of the Left value of the Either.
142+ * @param <T> The type of the Right value of the Either.
143+ * @return {@code Success(either.get())} if either {@link Either#isRight() is right}, otherwise {@code Failure(either.getLeft())} either {@link Either#isLeft() is left}.
144+ */
145+ public static <E extends Throwable , T > Try <T > ofEither (Either <E , T > either ) {
146+ Objects .requireNonNull (either , "either is null" );
147+ return either .fold (Try ::failure , Try ::success );
148+ }
149+
134150 /**
135151 * Creates a Try of a CheckedRunnable.
136152 *
Original file line number Diff line number Diff line change @@ -313,6 +313,24 @@ public void shouldThrowNullPointerExceptionWhenCallingTryOfCallable() {
313313 assertThatThrownBy (() -> Try .ofCallable (null )).isInstanceOf (NullPointerException .class ).hasMessage ("callable is null" );
314314 }
315315
316+ // -- Try.ofEither
317+
318+ @ Test
319+ public void shouldCreateSuccessWhenCallingTryOfEither () {
320+ assertThat (Try .ofEither (Either .right (1 )) instanceof Try .Success ).isTrue ();
321+ }
322+
323+ @ Test
324+ public void shouldThrowNullPointerExceptionWhenCallingTryOfEither () {
325+ assertThatThrownBy (() -> Try .ofEither (null )).isInstanceOf (NullPointerException .class ).hasMessage ("either is null" );
326+ }
327+
328+ @ Test
329+ public void shouldCreateFailureWhenCallingTryOfEither () {
330+ Either <Throwable ,Integer > x = Either .left (new NullPointerException ());
331+ assertThat (Try .ofEither (x ) instanceof Try .Failure ).isTrue ();
332+ }
333+
316334 // -- Try.run
317335
318336 @ Test
You can’t perform that action at this time.
0 commit comments