Coming across an pre-Java 8 example from jparsec, I wondered if I could leverage lambdas for a more expressive syntax.
Original example:
enum BinaryOperator implements Map2<Double,Double,Double> {
PLUS {
public Double map(Double a, Double b) {
return a + b;
}
},
MINUS {
public Double map(Double a, Double b) {
return a - b;
}
},
MUL {
public Double map(Double a, Double b) {
return a * b;
}
},
DIV {
public Double map(Double a, Double b) {
return a / b;
}
}
}
where
public interface Map2<A, B, T> {
/** Maps {@code a} and {@code b} to the target object. */
T map(A a, B b);
}
A plain Map2 instance is easily created with e.g. (a,b)->a+b
, but is there a concise way to do the same for enums implementing a single function interface?
My current solution looks like this, but it is still verbose:
enum BinaryOperator implements Map2<Double,Double,Double> {
PLUS((a, b) -> a + b), MINUS((a, b) -> a - b), MUL((a, b) -> a * b), DIV((a, b) -> a / b);
private final BiFunction<Double, Double, Double> f;
private BinaryOperator(BiFunction<Double, Double, Double> f) {
this.f = f;
}
@Override
public Double map(Double a, Double b) {
return f.apply(a, b);
}
}