-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContext.java
More file actions
56 lines (45 loc) · 1.32 KB
/
Context.java
File metadata and controls
56 lines (45 loc) · 1.32 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
45
46
47
48
49
50
51
52
53
54
55
56
package com.holi;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import static java.util.Arrays.asList;
/**
* Created by selonj on 16-9-9.
*/
@FunctionalInterface
public interface Context<T, R> {
R get(T name);
static <T, R> Context<T, R> failsWhenMissingValue(Context<T, R> context) {
return (name) -> {
R value = context.get(name);
if (value == null) throw new MissingValueException("missing variable `" + name + "`!");
return value;
};
}
static <T, R> Context<T, String> valueToString(Context<T, R> context) {
return (name) -> context.get(name).toString();
}
static <T, R> Context<T, R> from(Map<T, R> variables) {
return variables::get;
}
static <T, R> Context<T, R> from(Iterable<R> values) {
return from(values.iterator());
}
@SafeVarargs
static <T, R> Context<T, R> from(R... values) {
return from(asList(values));
}
static <T, R> Context<T, R> from(Iterator<R> values) {
return name -> values.hasNext() ? values.next() : null;
}
static Context<Integer, String> groups(final Matcher matcher) {
return new Context<Integer, String>() {
@Override public String get(Integer group) {
return matcher.group(group);
}
@Override public String toString() {
return "groups";
}
};
}
}