Java – can a bifunction reference be passed to a method of the desired functional interface?
I've only used java 6, and now I'm catching up to learn new features in Java 8 I read this article here:
It says:
Bifunction comp = (first, second) – > integer compare(first.length(),second. length());
However, when I see this post: how do you assign a lambda to a variable in Java 8?
The answer to the question there suggests that you can't do it exactly according to the quoted paragraph
So, is the information in the article incorrect, or did I read it wrong here?
thank you!
Solution
I don't see any content in the so answer of the link contradicting the article
The general rules of the type system apply to functional interfaces
If you declare a variable as bifunction < string, string, integer > bifunction, you cannot pass it to a method that requires comparator < string > Because bifunction < string, integer > is not a subtype of comparator < string >
The fact that the function type follows all the usual rules is to allow this new function to be added with minimal disturbance
If you want to make a comparator with bifunction, all you have to do is add:: apply:
BiFunction<String,Integer> bifunc = (a,b) -> Integer.compare(a.length(),b.length()); Arrays.sort(array,bifunc::apply);