Using enum values to represent binary operators (or functions)

Posted by Bears will eat you on Stack Overflow See other posts from Stack Overflow or by Bears will eat you
Published on 2010-03-11T19:22:39Z Indexed on 2010/03/11 19:24 UTC
Read the original article Hit count: 150

Filed under:
|
|

I'm looking for an elegant way to use values in a Java enum to represent operations or functions. My guess is, since this is Java, there just isn't going to be a nice way to do it, but here goes anyway. My enum looks something like this:

public enum Operator {
    LT,
    LTEQ,
    EQEQ,
    GT,
    GTEQ,
    NEQ;

    ...
}

where LT means < (less than), LTEQ means <= (less than or equal to), etc - you get the idea. Now I want to actually use these enum values to apply an operator. I know I could do this just using a whole bunch of if-statements, but that's the ugly, OO way, e.g.:

int a = ..., b = ...;
Operator foo = ...; // one of the enum values
if (foo == Operator.LT) {
    return a < b;
}
else if (foo == Operator.LTEQ) {
    return a <= b;
}
else if ... // etc

What I'd like to be able to do is cut out this structure and use some sort of first-class function or even polymorphism, but I'm not really sure how. Something like:

int a = ..., b = ...;
Operator foo = ...;
return foo.apply(a, b);

or even

int a = ..., b = ...;
Operator foo = ...;
return a foo.convertToOperator() b;

But as far as I've seen, I don't think it's possible to return an operator or function (at least, not without using some 3rd-party library). Any suggestions?

© Stack Overflow or respective owner

Related posts about java

Related posts about enum