File tree Expand file tree Collapse file tree 2 files changed +35
-1
lines changed
main/java/io/vavr/control
test/java/io/vavr/control Expand file tree Collapse file tree 2 files changed +35
-1
lines changed Original file line number Diff line number Diff line change 28
28
import java .util .NoSuchElementException ;
29
29
import java .util .Objects ;
30
30
import java .util .concurrent .Callable ;
31
- import java .util .function .*;
31
+ import java .util .function .Consumer ;
32
+ import java .util .function .Function ;
33
+ import java .util .function .Predicate ;
34
+ import java .util .function .Supplier ;
32
35
33
36
import static io .vavr .API .Match ;
34
37
import static io .vavr .control .TryModule .isFatal ;
@@ -131,6 +134,19 @@ public static <T> Try<T> ofCallable(Callable<? extends T> callable) {
131
134
return of (callable ::call );
132
135
}
133
136
137
+ /**
138
+ * Creates a Try of an Either.
139
+ *
140
+ * @param either Either which left type is a {@link Throwable}
141
+ * @param <E> The type of the Left value of the Either.
142
+ * @param <T> The type of the Right value of the Either.
143
+ * @return {@code Success(either.get())} if either {@link Either#isRight() is right}, otherwise {@code Failure(either.getLeft())} either {@link Either#isLeft() is left}.
144
+ */
145
+ public static <E extends Throwable , T > Try <T > ofEither (Either <E , T > either ) {
146
+ Objects .requireNonNull (either , "either is null" );
147
+ return either .fold (Try ::failure , Try ::success );
148
+ }
149
+
134
150
/**
135
151
* Creates a Try of a CheckedRunnable.
136
152
*
Original file line number Diff line number Diff line change @@ -313,6 +313,24 @@ public void shouldThrowNullPointerExceptionWhenCallingTryOfCallable() {
313
313
assertThatThrownBy (() -> Try .ofCallable (null )).isInstanceOf (NullPointerException .class ).hasMessage ("callable is null" );
314
314
}
315
315
316
+ // -- Try.ofEither
317
+
318
+ @ Test
319
+ public void shouldCreateSuccessWhenCallingTryOfEither () {
320
+ assertThat (Try .ofEither (Either .right (1 )) instanceof Try .Success ).isTrue ();
321
+ }
322
+
323
+ @ Test
324
+ public void shouldThrowNullPointerExceptionWhenCallingTryOfEither () {
325
+ assertThatThrownBy (() -> Try .ofEither (null )).isInstanceOf (NullPointerException .class ).hasMessage ("either is null" );
326
+ }
327
+
328
+ @ Test
329
+ public void shouldCreateFailureWhenCallingTryOfEither () {
330
+ Either <Throwable ,Integer > x = Either .left (new NullPointerException ());
331
+ assertThat (Try .ofEither (x ) instanceof Try .Failure ).isTrue ();
332
+ }
333
+
316
334
// -- Try.run
317
335
318
336
@ Test
You can’t perform that action at this time.
0 commit comments