Skip to content

Commit e027f67

Browse files
committed
Add Try.of(Either) factory method (see #2653).
1 parent 2f2304d commit e027f67

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/main/java/io/vavr/control/Try.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@
2828
import java.util.NoSuchElementException;
2929
import java.util.Objects;
3030
import 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

3336
import static io.vavr.API.Match;
3437
import 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
*

src/test/java/io/vavr/control/TryTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff 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

0 commit comments

Comments
 (0)