Skip to content

Commit 915f219

Browse files
committed
Add Either.toTry(L => Throwable)
1 parent 2f2304d commit 915f219

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -794,6 +794,22 @@ public final Validation<L, R> toValidation() {
794794
return isRight() ? Validation.valid(get()) : Validation.invalid(getLeft());
795795
}
796796

797+
/**
798+
* Transforms this {@code Either} into a {@link Try} instance.
799+
* <p>
800+
* Map this {@code left} value to a {@link Throwable} using the {@code leftMapper}
801+
* or return a {@link Try#success(Object) Success} of this {@code right} value.
802+
* </p>
803+
*
804+
* @param leftMapper A function that maps the left value of this {@code Either} to a {@link Throwable} instance
805+
* @return A {@link Try} instance that represents the result of the transformation
806+
* @throws NullPointerException if {@code leftMapper} is {@code null}
807+
*/
808+
public final Try<R> toTry(Function<? super L, ? extends Throwable> leftMapper) {
809+
Objects.requireNonNull(leftMapper, "leftMapper is null");
810+
return mapLeft(leftMapper).fold(Try::failure,Try::success);
811+
}
812+
797813
// -- Left/Right projections
798814

799815
/**

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,22 @@ public void shouldConvertToInvalidValidation() {
571571
assertThat(validation.getError()).isEqualTo("vavr");
572572
}
573573

574+
// -- toTry
575+
576+
@Test
577+
public void shouldConvertToSuccessTry() {
578+
final Try<Integer> actual = Either.right(42).toTry(left -> new IllegalStateException(Objects.toString(left)));
579+
assertThat(actual.isSuccess()).isTrue();
580+
assertThat(actual.get()).isEqualTo(42);
581+
}
582+
583+
@Test
584+
public void shouldConvertToFailureTry() {
585+
final Try<?> actual = Either.left("vavr").toTry(left->new IllegalStateException(left));
586+
assertThat(actual.isFailure()).isTrue();
587+
assertThat(actual.getCause().getMessage()).isEqualTo("vavr");
588+
}
589+
574590
// hashCode
575591

576592
@Test

0 commit comments

Comments
 (0)