summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/graph/GenHolder.java
blob: df363faed7dc9333c87b4bf5f4c2a83deeb53293 (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package bjc.utils.graph;

import java.util.function.Function;

/**
 * Holds a single value of a specific type. This is used for indirect
 * references to data, and more specifically for accessing non-final
 * variables from a lambda. AKA the identity monad
 * 
 * @author ben
 *
 * @param <T>
 *            The type of the data being held
 */
public class GenHolder<T> {
	/**
	 * The state this holder is responsible for.
	 */
	public T held;

	/**
	 * Creates a new empty holder, with its state set to null
	 */
	public GenHolder() {
		held = null;
	}

	/**
	 * Creates a new holder, with its state initialized to the provided
	 * value
	 * 
	 * @param held
	 *            The state to initialize this holder to.
	 */
	public GenHolder(T hld) {
		held = hld;
	}

	/**
	 * Apply the given transformation to the held value. Returns the holder
	 * for allowing chaining of transforms
	 * 
	 * @param f
	 *            The transform to apply to the value
	 * @return The holder
	 */
	public GenHolder<T> transform(Function<T, T> f) {
		held = f.apply(held);

		return this;
	}

	/**
	 * Return the result of applying the given transformation to the held
	 * value Doesn't change the held value
	 * 
	 * @param f
	 *            The transformation to apply
	 * @return A holder with the transformed value
	 */
	public <NewT> GenHolder<NewT> map(Function<T, NewT> f) {
		return new GenHolder<NewT>(f.apply(held));
	}

	/**
	 * Returns a raw mapped value, not contained in a GenHolder
	 * 
	 * @param f
	 *            The function to use for mapping the value
	 * @return The mapped value outside of a GenHolder
	 */
	public <E> E unwrap(Function<T, E> f) {
		return f.apply(held);
	}
}