1
2
3
4
5
6
7 package com.varmateo.yawg.util;
8
9 import java.util.function.BiFunction;
10 import java.util.function.Supplier;
11
12 import io.vavr.control.Try;
13
14
15
16
17
18 public final class Trys {
19
20
21
22
23
24 private Trys() {
25
26 }
27
28
29
30
31
32 public static Try<Void> success() {
33
34 return Try.success(null);
35 }
36
37
38
39
40
41 public static <T> Try<T> flatten(final Try<Try<T>> x) {
42
43 if ( x.isSuccess() ) {
44 return x.get();
45 } else {
46 return Try.failure(x.getCause());
47 }
48 }
49
50
51
52
53
54
55
56
57
58
59
60 public static <T, U, R> Try<R> apply(
61 final BiFunction<T, U, Try<R>> f,
62 final Try<T> x,
63 final Try<U> y) {
64
65 if ( x.isSuccess() ) {
66 if ( y.isSuccess() ) {
67 return flatten(Try.of(() -> f.apply(x.get(), y.get())));
68 } else {
69 return Try.failure(y.getCause());
70 }
71 } else {
72 return Try.failure(x.getCause());
73 }
74 }
75
76
77
78
79
80
81
82
83
84
85
86 public static <T, U, R> Try<R> apply(
87 final BiFunction<T, U, Try<R>> f,
88 final Supplier<Try<T>> x,
89 final Supplier<Try<U>> y) {
90
91 final Try<T> xResult = flatten(Try.of(() -> x.get()));
92
93 if ( xResult.isSuccess() ) {
94 final Try<U> yResult = flatten(Try.of(() -> y.get()));
95
96 if ( yResult.isSuccess() ) {
97 return flatten(Try.of(() -> f.apply(xResult.get(), yResult.get())));
98 } else {
99 return Try.failure(yResult.getCause());
100 }
101 } else {
102 return Try.failure(xResult.getCause());
103 }
104 }
105
106 }