Search code examples
javajava-8functional-interfacejavacompiler

Does java compiler convert Function<Double,Integer> to DoubleToIntFunction?


Function<Double,Integer> f1=(d)-> {
        if(d>5)
            return 0;
        return 1;
    };
DoubleToIntFunction f2=(d)-> {
        if(d>5)
            return 1;
        return 0;
    };
double d=5.0;
f1.apply(d);
f2.applyAsInt(d);

Will f1 be optimized into DoubleToIntFunction(someting like f2).


Solution

  • I don't see how it could, the upper lambda allows nulls while the lower one doesn't. The compiler would have to do a ton of static code analysis to see if a null could ever be passed to the Function in order to optimize it.

    f1.apply(null); //works!
    f2.applyAsInt(null); //won't compile!