Redundant Code Problem
If you are working on mathematical program, you might have written code for creating new Function object from source function object.
For example, creating new function "g(x)" which is defined as "f(x) - target"
Before Java 8, this kind of creating new function object needs redundant code as below:
// using anonymous inner class public final static Function subtract(Function f, double target) { return new Function() { @Override public double f(double x) { return f.f(x) - target; } }; } // function interface definition public interface Function { double f(double x); }
Of course, the code is perfect but the redundant part "new Function()..." prevent developers understanding core logic part quickly.
Lambda Expression
Now in Java 8, "lambda expression" helps reducing this kind of redundant code. See below code which uses lambda expression.
public final static Function subtract(Function f, double target) { return x -> f.f(x) - target; }
コメント