I am trying to understand functional interfaces in Java 8. Suppose f() to the functor:
public class A {
private double a;
public A(double a_) {
a = a_;
}
public void f(double[] b, double[] c, double[] d) {
d[0] = a * (b[0] + c[0]);
}
}
Is it possible to create a similar construction using the Java 8 functional interface ?
public class B {
public double g(Function funct, double[] b, double[] c, double[] d) {
funct(b, c, d); //Call the functor, minor calculations
return d[0];
}
public static void main(String[] args) {
A a = new A(1);
double[] b = {2};
double[] c = {3};
double[] d = {4};
double res = g(a.f, b, c, d);
}
}
In other word,is it possible to use a specific method of the object (or a static method) as a functor? If so, could you give a short example?
The functor represent an illustration of the function working with a data member (a) and some additional parameters (b, c, d )...
I found the following solution. Initially, the interface IFunction is created:
public interface IFunction {
double eval(double [] a, double [] b, double [] c) ;
}
The class A remains:
public class A {
private double a;
public A(double a_) {a = a_;}
public void f(double[] b, double[] c, double[] d) {
d[0] = a * (b[0] + c[0]);
}
}
However, the class B uses a function pointer:
public class B {
public double g(IFunction funct, double[] b, double[] c, double[] d) {
funct.eval(b, c, d);
return d[0];
}
public static void main(String[] args) {
A a = new A(1);
double[] b = {2};
double[] c = {3};
double[] d = {4};
double res = g(a::f, b,c, d);
}
I hope it helps... Maybe,there is a better solution :-)