diff --git a/src/main/java/io/vavr/control/Either.java b/src/main/java/io/vavr/control/Either.java index 8ac97ecf9..020950405 100644 --- a/src/main/java/io/vavr/control/Either.java +++ b/src/main/java/io/vavr/control/Either.java @@ -794,6 +794,22 @@ public final Validation toValidation() { return isRight() ? Validation.valid(get()) : Validation.invalid(getLeft()); } + /** + * Transforms this {@code Either} into a {@link Try} instance. + *

+ * Map this {@code left} value to a {@link Throwable} using the {@code leftMapper} + * or return a {@link Try#success(Object) Success} of this {@code right} value. + *

+ * + * @param leftMapper A function that maps the left value of this {@code Either} to a {@link Throwable} instance + * @return A {@link Try} instance that represents the result of the transformation + * @throws NullPointerException if {@code leftMapper} is {@code null} + */ + public final Try toTry(Function leftMapper) { + Objects.requireNonNull(leftMapper, "leftMapper is null"); + return mapLeft(leftMapper).fold(Try::failure,Try::success); + } + // -- Left/Right projections /** diff --git a/src/test/java/io/vavr/control/EitherTest.java b/src/test/java/io/vavr/control/EitherTest.java index 725433d6e..ed26cd889 100644 --- a/src/test/java/io/vavr/control/EitherTest.java +++ b/src/test/java/io/vavr/control/EitherTest.java @@ -571,6 +571,22 @@ public void shouldConvertToInvalidValidation() { assertThat(validation.getError()).isEqualTo("vavr"); } + // -- toTry + + @Test + public void shouldConvertToSuccessTry() { + final Try actual = Either.right(42).toTry(left -> new IllegalStateException(Objects.toString(left))); + assertThat(actual.isSuccess()).isTrue(); + assertThat(actual.get()).isEqualTo(42); + } + + @Test + public void shouldConvertToFailureTry() { + final Try actual = Either.left("vavr").toTry(left->new IllegalStateException(left)); + assertThat(actual.isFailure()).isTrue(); + assertThat(actual.getCause().getMessage()).isEqualTo("vavr"); + } + // hashCode @Test