Search code examples
javac++interfaceoperatorsfunctor

C++ functors to Java, overloading operator ()()


Suppose a simple example of functors in C++:

class Test2 {
    private:
        double a;

    public:
        Test2 (double a_) : a(a_){}
        double operator () () {return 10*a;}
};

template <typename Function>
double test ( Function function ) {return function();}

int main(int argc,  char* argv[]) {
    double a = test( Test2(5) );
    return 0;
}

Is there any way to implement this construction in Java (for example using the interface Functor)? Could you give me a short example? Thanks for your help.


Solution

  • In Java 8, you can use the DoubleSupplier interface to get a double value from an object:

    public class Test implements DoubleSupplier {
        private double a;
        public Test(double a) { this.a = a; }
        public double getAsDouble() { return 10 * a; }
    
        public static double test(DoubleSupplier ds) { 
            return ds.getAsDouble();
        }
        public static void main(String[] args) {
            double a = test(new Test(5));
        }
    }
    

    If you aren't using Java 8, then you could just make your own interface to implement from:

    public interface MyDoubleSupplier {
        double getAsDouble();
    }