Skip to content

Propose Either.toTry(L => Throwable) #2734

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/main/java/io/vavr/control/Either.java
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,22 @@ public final Validation<L, R> toValidation() {
return isRight() ? Validation.valid(get()) : Validation.invalid(getLeft());
}

/**
* Transforms this {@code Either} into a {@link Try} instance.
* <p>
* 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.
* </p>
*
* @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<R> toTry(Function<? super L, ? extends Throwable> leftMapper) {
Objects.requireNonNull(leftMapper, "leftMapper is null");
return mapLeft(leftMapper).fold(Try::failure,Try::success);
}

// -- Left/Right projections

/**
Expand Down
16 changes: 16 additions & 0 deletions src/test/java/io/vavr/control/EitherTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,22 @@ public void shouldConvertToInvalidValidation() {
assertThat(validation.getError()).isEqualTo("vavr");
}

// -- toTry

@Test
public void shouldConvertToSuccessTry() {
final Try<Integer> 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
Expand Down