1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.functor.core.composite;
18
19 import java.io.Serializable;
20
21 import org.apache.commons.functor.Function;
22 import org.apache.commons.functor.Predicate;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public final class ConditionalFunction<T> implements Function<T>, Serializable {
45
46
47
48 private static final long serialVersionUID = 4214871352184887792L;
49
50
51 private static final int HASH_SHIFT = 4;
52
53
54 private final Predicate ifPred;
55 private final Function<? extends T> thenFunc;
56 private final Function<? extends T> elseFunc;
57
58
59
60
61
62
63
64
65
66 public ConditionalFunction(Predicate ifPred, Function<? extends T> thenFunc, Function<? extends T> elseFunc) {
67 if (ifPred == null) {
68 throw new IllegalArgumentException("Predicate argument was null");
69 }
70 this.ifPred = ifPred;
71 if (thenFunc == null || elseFunc == null) {
72 throw new IllegalArgumentException("One or more Function arguments was null");
73 }
74 this.thenFunc = thenFunc;
75 this.elseFunc = elseFunc;
76 }
77
78
79
80
81
82
83 public T evaluate() {
84 if (ifPred.test()) {
85 return thenFunc.evaluate();
86 } else {
87 return elseFunc.evaluate();
88 }
89 }
90
91
92
93
94 public boolean equals(Object that) {
95 return that == this || (that instanceof ConditionalFunction<?> && equals((ConditionalFunction<?>) that));
96 }
97
98
99
100
101
102
103 public boolean equals(ConditionalFunction<?> that) {
104 return null != that
105 && (null == ifPred ? null == that.ifPred : ifPred.equals(that.ifPred))
106 && (null == thenFunc ? null == that.thenFunc : thenFunc.equals(that.thenFunc))
107 && (null == elseFunc ? null == that.elseFunc : elseFunc.equals(that.elseFunc));
108 }
109
110
111
112
113 public int hashCode() {
114 int hash = "ConditionalFunction".hashCode();
115 if (null != ifPred) {
116 hash <<= HASH_SHIFT;
117 hash ^= ifPred.hashCode();
118 }
119 if (null != thenFunc) {
120 hash <<= HASH_SHIFT;
121 hash ^= thenFunc.hashCode();
122 }
123 if (null != elseFunc) {
124 hash <<= HASH_SHIFT;
125 hash ^= elseFunc.hashCode();
126 }
127 return hash;
128 }
129
130
131
132
133 public String toString() {
134 return "ConditionalFunction<" + ifPred + "?" + thenFunc + ":" + elseFunc + ">";
135 }
136
137 }