Is it possible to define a method on the Proto enum?

Viewed 229

Say I have a Proto buffer enum operations.proto

enum Operation {
  UNSPECIFIED = 0;
  PLUS = 1;
  MINUS = 2;
  TIMES = 3;
  DIVIDE = 4;
}

So in my Java code, I have to do something like

if (operation == Operation.PLUS) {
  return x+y;
} else if (operation == Operation.MINUS) {
  return x-y;
}
...

And I know I can do better with "Effective Java Item 34: Use enums instead of int constants" to have a method on the enum type like

public enum Operation {
  PLUS {public double apply(double x, double y){return x + y;}},
  MINUS {public double apply(double x, double y){return x - y;}},
  TIMES {public double apply(double x, double y){return x * y;}},
  DIVIDE{public double apply(double x, double y){return x / y;}};
  public abstract double apply(double x, double y);
}

However, my Operation is a proto enum instead of java enum. I can imagine I can map the proto enum to Java enum and define methods on the Java enum (not sure if this overcomplicates the issue). But is there any smart way to achieve this?

1 Answers

No, that is not a thing that the schema DSL allows.

This exists for services, but that is thinking of things like gRPC.

Related