How I can get arithmetical operators at run-time in Java? Suppose if I have values
ADDit should add the numberMULthen it should multiply the number
For Example
public calculate(int x, String str){
while(str.equals("some value")){
If( str.equals("ADD"))
// it should return me something like x+
if( str.equals("MUL"))
it return me something like x*
}
if( str.equals("FINAL"))
it should return me x+x*x
}
What you need is not runtime metaprogramming, but first class functions.
The following represent first class functions, with arity 1 and 2 respectively.
For the sake of simplicity, let’s use specialized versions of above classes.
Now construct a dictionary of the required arithmetic operations.
Add a method that partially applies
BinaryOperationon one parameter.Now we can write your
calculatemethod.Use:
The abstractions used in the above solution, namely first class function interfaces and partial application, are both available in this library.