File tree Expand file tree Collapse file tree 2 files changed +32
-0
lines changed
main/java/io/vavr/control
test/java/io/vavr/control Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -794,6 +794,22 @@ public final Validation<L, R> toValidation() {
794
794
return isRight () ? Validation .valid (get ()) : Validation .invalid (getLeft ());
795
795
}
796
796
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
+
797
813
// -- Left/Right projections
798
814
799
815
/**
Original file line number Diff line number Diff line change @@ -571,6 +571,22 @@ public void shouldConvertToInvalidValidation() {
571
571
assertThat (validation .getError ()).isEqualTo ("vavr" );
572
572
}
573
573
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
+
574
590
// hashCode
575
591
576
592
@ Test
You can’t perform that action at this time.
0 commit comments