javajava-8java-streamfunctional-interface

Difference between BiFunction<X, X> and BinaryOperator<X>


I am not able to understand that how come BinaryOperator<Integer> could be placed at the place of A in the code below, but not BiFunction<Integer, Integer>?

A foo = (a, b) -> { return a * a + b * b; };
int bar = foo.apply(2, 3);
System.out.println(bar);

Could someone please help me understand it.


Solution

  • BinaryOperator is a special BiFunction. So you can assign the same expression to both of them. Check this out.

    BinaryOperator<Integer> foo = (a, b) -> {
        return a * a + b * b;
    };
    BiFunction<Integer, Integer, Integer> barFn = (a, b) -> {
        return a * a + b * b;
    };
    

    If you look at the source code, it would be

    public interface BinaryOperator<T> extends BiFunction<T,T,T> {
       // Remainder omitted.
    }