summaryrefslogtreecommitdiff
path: root/base/src/main/java/bjc/utils/funcutils/Isomorphism.java
blob: d86ee9ffd2c499f8cd4d9404f8d09c2282af836b (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
package bjc.utils.funcutils;

import java.util.function.Function;

/**
 * A pair of functions to transform between a pair of types.
 * 
 * @author bjculkin
 * 
 * @param <S>
 * 	The source type of the isomorphism.
 * 
 * @param <D>
 * 	The destination type of isomorphism.
 */
public class Isomorphism<S, D> {
	/* The function to the destination type. */
	private Function<S, D>	toFunc;
	/* The function to the source type. */
	private Function<D, S>	fromFunc;

	/**
	 * Create a new isomorphism.
	 * 
	 * @param to
	 * 	The 'forward' function, from the source to the definition.
	 * 
	 * @param from
	 * 	The 'backward' function, from the definition to the source.
	 */
	public Isomorphism(Function<S, D> to, Function<D, S> from) {
		toFunc = to;
		fromFunc = from;
	}

	/**
	 * Apply the isomorphism forward.
	 * 
	 * @param val
	 * 	The source value.
	 * 
	 * @return
	 * 	The destination value.
	 */
	public D to(S val) {
		return toFunc.apply(val);
	}

	/**
	 * Apply the isomorphism backward.
	 * 
	 * @param val
	 * 	The destination value.
	 * 
	 * @return
	 * 	The source value.
	 */
	public S from(D val) {
		return fromFunc.apply(val);
	}
}