2

As of Java 8, method references exist. I have a simple interface which I would like to use existing (preferably in a java.something package) method references to implement.

public class Calculator {
    private interface BinaryFunction<A, B, R> {
        R apply(A a, B b);
    }

    private <A, B, R> R apply(BinaryFunction<A, B, R> binaryFunction, A a, B b) {
        return binaryFunction.apply(a, b);
    }

    public static void main(String [] args) {
        Calculator calculator = new Calculator();
        calculator.apply((a, b) -> a + b, 1, 2);            // 3
        calculator.apply(Math::addExact, 1, 2);             // 3
        calculator.apply((a, b) -> a || b, true, false);    // true
//        calculator.apply(?::?, true, false);              // true
    }
}

Math::addExact isn't the same as +, but it's close enough for me--I actually prefer getting ArithmeticException("integer overflow") thrown for my purposes.

If this were Python, I'd use the operator module, but I don't know if there is such a thing in Java.

So is there any static method in a java.something package that can go in the ?::? part which is equivalent to the || operator?

2
  • Are you asking for a method that does || on a pair of inputs? Commented Jun 28, 2016 at 5:54
  • @dimo414 Yeah. And it ought to be in a built-in package. Commented Jun 28, 2016 at 5:58

1 Answer 1

3

I use the java.lang.Boolean.logicalOr(boolean, boolean) method for this purpose.

So in your case you would use:

calculator.apply(Boolean::logicalOr, true, false);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.