我一直只使用 Java 6,现在正 catch 学习 Java 8 中的新功能。我在这里阅读了这篇文章: http://www.drdobbs.com/jvm/lambda-expressions-in-java-8/240166764?pgno=2
它说:
The Java API defines several generic functional interfaces in the java.util.function package. One of the interfaces, BiFunction, describes functions with parameter types T and U and return type R. You can save our string comparison lambda in a variable of that type:
BiFunction<String, String, Integer> comp
= (first, second) -> Integer.compare(first.length(), second.length());
However, that does not help you with sorting. There is no Arrays.sort method that wants a BiFunction. If you have used a functional programming language before, you may find this curious. But for Java programmers, it's pretty natural. An interface such as Comparator has a specific purpose, not just a method with given parameter and return types. Java 8 retains this flavor. When you want to do something with lambda expressions, you still want to keep the purpose of the expression in mind, and have a specific functional interface for it.
但是,当我看到这个线程时: How do you assign a lambda to a variable in Java 8?
那里的问题的答案建议按照引用的段落所说的做你不能做的事情。
那么,是文章中的信息不正确,还是我误读了这里的内容?
谢谢!
最佳答案
我在链接的 SO 答案中没有看到任何与文章相矛盾的内容。
类型系统的常规规则适用于功能接口(interface)。
如果您将变量声明为 BiFunction<String,String,Integer> bifunc
, 您将不允许将其传递给需要 Comparator<String>
的方法因为BiFunction<String,String,Integer>
不是 Comparator<String>
的子类型 .
函数类型遵循所有常用规则这一事实使得这种新功能能够以最小的扰动添加。
如果你想制作一个Comparator
从一个BiFunction
您所要做的就是添加 ::apply
像这样:
BiFunction<String,String,Integer> bifunc = (a,b) ->
Integer.compare(a.length(), b.length());
Arrays.sort(array, bifunc::apply);
关于java - BiFunction 引用可以传递给需要功能接口(interface)的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28336350/