As pointed out here lambdas provide a quite elegant way of specifying behaviour for individual enum values.
Before Java 8 I would normally have implemented this as:
enum Operator {
TIMES {
public int operate(int n1, int n2) {
return n1 * n2;
}
},
PLUS {
public int operate(int n1, int n2) {
return n1 + n2;
}
};
public int operate(int n1, int n2) {
throw new AssertionError();
}
}
Now I tend to use:
enum Operator {
TIMES((n1, n2) -> n1 * n2),
PLUS((n1, n2) -> n1 + n2);
private final BinaryOperator<Integer> operation;
private Operator(BinaryOperator<Integer> operation) {
this.operation = operation;
}
public int operate(int n1, int n2) {
return operation.apply(n1, n2);
}
}
This seems significantly more elegant.
I cannot think of a reason to override methods for a specific enum value now. So my question is, are there any good reasons to use method overrides in an enum
now or should a functional interface always be preferred?