For Dart 2.17, we can use constructors in enum similarly to how we do with classes.
I am trying to insert an anonymous function inside of an enum directly.
here is code that works but doesn't do exactly what I'd like it to do.
int _add(int a, int b) => a + b;
int _sub(int a, int b) => a - b;
int _mul(int a, int b) => a * b;
double _div(int a, int b) => a / b;
enum MyEnum {
addition(_add),
subtract(_sub),
multiplication(_mul),
division(_div);
final Function fx;
const MyEnum(this.fx);
}
void main() {
var fun = MyEnum.addition;
print(fun.fx(1, 2));
fun = MyEnum.subtract;
print(fun.fx(1, 2));
fun = MyEnum.multiplication;
print(fun.fx(1, 2));
fun = MyEnum.division;
print(fun.fx(1, 2));
}
Instead of making a function somewhere else in the code, as the _add, _sub, _mul, _div, I would like to directly insert an anonymous function into the enum, like in the following code (please note that the following code does not work).
What I'd like to do
enum MyEnum {
// I'd like to insert an anonymous function instead.
addition((int a, int b) => _add(a, b)),
subtract((int a, int b) => a - b),
multiplication(int a, int b) => a * b),
division((int a, int b) => a / b;);
final Function fx;
const MyEnum(this.fx);
}
Is it possible? Would anyone be able to show me how to do this? I cannot figure out what I am doing wrong.