0

I wanted to rewrite this code from Java to Apex is it possible?

public enum Operator
{
    ADDITION("+") {
       @Override public double apply(double x1, double x2) {
        return x1 + x2;
       }
    },
    SUBTRACTION("-") {
       @Override public double apply(double x1, double x2) {
        return x1 - x2;
       }
    };
    // You'd include other operators too...

    private final String text;

   private Operator(String text) {
    this.text = text;
   }

   // Yes, enums *can* have abstract methods. This code compiles...
   public abstract double apply(double x1, double x2);
}

And how will I call this enum Operator? Is it possible to declare this inside my Apex Class? If possible, how will I call the enum function?

1 Answer 1

2

You can write a similar piece of code, but you can't replicate this annotation feature from Java.

In Apex I can see this working with ifs statements inside the apply method. "If plus sign, then sum, if minus sign, subtract, otherwise do nothing"

public class Operator {

    public String op_sign;

    public Operator (String op_sign) {
        this.op_sign = op_sign;
    }

    public Decimal apply (Decimal a, Decimal b) {
        if (this.op_sign == '+') {
            return a + b;
        } else if (this.op_sign == '-') {
            return a - b;
        } else {
            throw new UnsupportedOperationException('Unsupported operation.');
        }
    }
}
Decimal result = new Operator('+').apply(10, 20); // result = 30.0

There's this list of supported Apex annotations.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .