Java Reference
In-Depth Information
The basic pattern of all unit conversion is as follows:
1 . Multiply by the conversion factor.
2 . Adjust the baseline if relevant.
You can express this pattern with the following general method:
static double converter(double x, double f, double b) {
return x * f + b;
}
Here x is the quantity you want to convert, f is the conversion factor, and b is the baseline. But
this method is a bit too general. You'll typically find you require a lot of conversions between the
same pair of units, kilometers to miles, for example. You could obviously call the converter
method with three arguments on each occasion, but supplying the factor and baseline each time
would be tedious and you might accidentally mistype them.
You could write a completely new method for each application, but that would miss the reuse of
the underlying logic.
Here's an easy way to benefit from the existing logic while tailoring the converter for particular
applications. You can define a “factory” that manufactures one-argument conversion functions
to exemplify the idea of currying. Here it is:
static DoubleUnaryOperator curriedConverter(double f, double b){
return (double x) -> x * f + b;
}
Now all you have to do is pass it the conversion factor and baseline (f and b), and it will
obligingly return a function (of x) to do exactly what you asked for. For example, you can now
use the factory to produce any converter you require:
DoubleUnaryOperator convertCtoF = curriedConverter(9.0/5, 32);
DoubleUnaryOperator convertUSDtoGBP = curriedConverter(0.6, 0);
DoubleUnaryOperator convertKmtoMi = curriedConverter(0.6214, 0);
Because DoubleUnaryOperator defines a method applyAsDouble, you can use your converters as
follows:
 
Search WWH ::




Custom Search