gpt4 book ai didi

java - BiFunction 引用可以传递给需要功能接口(interface)的方法吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:00:22 51 4
gpt4 key购买 nike

我一直只使用 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/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com