Java Reference
In-Depth Information
Note that you can't write something as simple as
integrate(x+10, 3, 7)
for two reasons. First, the scope of x is unclear, and second, this would pass a value of x+10 to
integrate instead of passing the function f.
Indeed, the secret role of dx in mathematics is to say “that function taking argument x whose
result is x+10.”
3.9.2. Connecting to Java 8 lambdas
Now, as we mentioned earlier, Java 8 uses the notation (double x) -> x+10 (a lambda expression)
for exactly this purpose; hence you can write
integrate((double x) -> x + 10, 3, 7)
or
integrate((double x) -> f(x), 3, 7)
or, using a method reference as mentioned earlier, simply
integrate(C::f, 3, 7)
if C is a class containing f as a static method. The idea is that you're passing the code for f to the
method integrate.
You may now wonder how you'd write the method integrate itself. Continue to suppose that f is
a linear function (straight line). You'd probably like to write in a form similar to mathematics:
But because lambda expressions can be used only in a context expecting a functional interface
(in this case, Function), you have to write it this way:
public double integrate( DoubleFunction<Double> f, double a, double b) {
return (f .apply (a) + f. apply (b)) * (b-a) / 2.0;
}
 
Search WWH ::




Custom Search