-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternMatching.java
More file actions
36 lines (27 loc) · 925 Bytes
/
PatternMatching.java
File metadata and controls
36 lines (27 loc) · 925 Bytes
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
package net.reservoircode.structures;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import static java.util.Optional.empty;
import static java.util.Optional.of;
@FunctionalInterface
public interface PatternMatching<T, R> {
Optional<R> matches(T value);
static <T, R> PatternMatching<T, R> when(
Predicate<T> predicate,
Function<T, R> action) {
return value -> predicate.test(value) ? of(action.apply(value)) : empty();
}
default PatternMatching<T, R> orWhen(
Predicate<T> predicate,
Function<T, R> action) {
return value -> {
final Optional<R> result = matches(value);
if (result.isPresent()) {
return result;
}
return (predicate.test(value)) ?
of(action.apply(value)) : empty();
};
}
}