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.BinaryFunction;
22 import org.apache.commons.functor.BinaryPredicate;
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 ConditionalBinaryFunction<L, R, T> implements BinaryFunction<L, R, T>, Serializable {
45
46
47
48 private static final long serialVersionUID = -994698971284481482L;
49
50
51 private static final int HASH_SHIFT = 4;
52
53
54 private final BinaryPredicate<? super L, ? super R> ifPred;
55 private final BinaryFunction<? super L, ? super R, ? extends T> thenFunc;
56 private final BinaryFunction<? super L, ? super R, ? extends T> elseFunc;
57
58
59
60
61
62
63
64
65
66 public ConditionalBinaryFunction(BinaryPredicate<? super L, ? super R> ifPred,
67 BinaryFunction<? super L, ? super R, ? extends T> thenFunc,
68 BinaryFunction<? super L, ? super R, ? extends T> elseFunc) {
69 if (ifPred == null) {
70 throw new IllegalArgumentException("BinaryPredicate argument was null");
71 }
72 if (thenFunc == null || elseFunc == null) {
73 throw new IllegalArgumentException("One or more BinaryFunction arguments was null");
74 }
75 this.ifPred = ifPred;
76 this.thenFunc = thenFunc;
77 this.elseFunc = elseFunc;
78 }
79
80
81
82
83
84
85 public T evaluate(L left, R right) {
86 if (ifPred.test(left, right)) {
87 return thenFunc.evaluate(left, right);
88 } else {
89 return elseFunc.evaluate(left, right);
90 }
91 }
92
93
94
95
96 public boolean equals(Object that) {
97 return that == this || (that instanceof ConditionalBinaryFunction<?, ?, ?>
98 && equals((ConditionalBinaryFunction<?, ?, ?>) that));
99 }
100
101
102
103
104
105
106 public boolean equals(ConditionalBinaryFunction<?, ?, ?> that) {
107 return null != that
108 && (null == ifPred ? null == that.ifPred : ifPred.equals(that.ifPred))
109 && (null == thenFunc ? null == that.thenFunc : thenFunc.equals(that.thenFunc))
110 && (null == elseFunc ? null == that.elseFunc : elseFunc.equals(that.elseFunc));
111 }
112
113
114
115
116 public int hashCode() {
117 int hash = "ConditionalBinaryFunction".hashCode();
118 if (null != ifPred) {
119 hash <<= HASH_SHIFT;
120 hash ^= ifPred.hashCode();
121 }
122 if (null != thenFunc) {
123 hash <<= HASH_SHIFT;
124 hash ^= thenFunc.hashCode();
125 }
126 if (null != elseFunc) {
127 hash <<= HASH_SHIFT;
128 hash ^= elseFunc.hashCode();
129 }
130 return hash;
131 }
132
133
134
135
136 public String toString() {
137 return "ConditionalBinaryFunction<" + ifPred + "?" + thenFunc + ":" + elseFunc + ">";
138 }
139
140 }