Skip to content
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

Propose Try.toEither(Throwable => L) #2724

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
20 changes: 18 additions & 2 deletions src/main/java/io/vavr/control/Try.java
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,22 @@ public final Either<Throwable, T> toEither() {
}
}

/**
* Converts this {@code Try} to an {@link Either}, converting the Throwable (in the failure case)
* to a left value using the passed {@link Function}.
*
* @param <L> left type of the resulting Either
* @param throwableMapper A transformation from throwable to the left type of the new {@code Either}
* @return A new {@code Either}
*/
public final <L> Either<L, T> toEither(Function<? super Throwable, ? extends L> throwableMapper) {
if (isFailure()) {
return Either.left(throwableMapper.apply(getCause()));
} else {
return Either.right(get());
}
}

/**
* Converts this {@code Try} to a {@link Validation}.
*
Expand All @@ -1142,8 +1158,8 @@ public final Validation<Throwable, T> toValidation() {
}

/**
* Converts this {@code Try} to a {@link Validation}, converting the Throwable (if present)
* to another object using passed {@link Function}.
* Converts this {@code Try} to a {@link Validation}, converting the Throwable (in the failure case)
* to another object using the passed {@link Function}.
*
* <pre>{@code
* Validation<String, Integer> = Try.of(() -> 1/0).toValidation(Throwable::getMessage));
Expand Down
7 changes: 7 additions & 0 deletions src/test/java/io/vavr/control/TryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -969,6 +969,13 @@ public void shouldConvertFailureToEitherLeftSupplier() {
assertThat(failure().toEither(() -> "test").isLeft()).isTrue();
}

@Test
public void shouldConvertFailureToEitherLeftMapper() {
final Try<Object> failure = Try.failure(new RuntimeException("a certain value"));
final Either<String, Object> either = failure.toEither(Throwable::getMessage);
assertThat(either).isEqualTo(Either.left("a certain value"));
}


// -- toValidation

Expand Down