-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEither.java
More file actions
44 lines (34 loc) · 1.01 KB
/
Either.java
File metadata and controls
44 lines (34 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.function.Function;
public class Either<L, R> {
private final L left;
private final R right;
private Either(L left, R right) {
this.left = left;
this.right = right;
}
public static <L, R> Either<L, R> left(L value) {
return new Either<>(value, null);
}
public static <L, R> Either<L, R> right(R value) {
return new Either<>(null, value);
}
public L getLeft() {
return left;
}
public R getRight() {
return right;
}
public boolean isLeft() {
return left != null;
}
public boolean isRight() {
return right != null;
}
public <U> Either<L, U> map(Function<? super R, ? extends U> fn) {
if (right == null) return Either.left(left);
return Either.right(fn.apply(right));
}
public <T> T match(Function<? super L, ? extends T> leftFn, Function<? super R, ? extends T> rightFn) {
return isRight() ? rightFn.apply(right) : leftFn.apply(left);
}
}