我知道,如果引用的方法采用与功能接口(interface)相同数量的参数并返回相同的类型,则方法引用可用于实现功能接口(interface),但为什么在某些情况下引用的方法的参数数量与函数接口(interface)的参数数量不同功能接口(interface)但仍然兼容?
我有一个简单的 BiConsumer,我尝试使用方法引用来实现它。我知道只要参数数量匹配,我也可以使用 lambda 表达式。我将展示代码以清楚地解释它。
我有一个BiConsumer<ArrayList<String>, ? super String>
我想实现。
Lambda 表达式的实现方法是:
BiConsumer<ArrayList<String>, ? super String> b = (firstArg,secondArg) -> firstArg.add(secondArg);
因为它们都需要 2 个输入参数,所以没有问题。
但是为什么BiConsumer<ArrayList<String>, ? super String> a = ArrayList::add;
还兼容吗? add
ArrayList 上的方法只需要 1 个输入参数,但功能接口(interface)需要 2 个。
任何答案将不胜感激。谢谢!
最佳答案
15.12.2.1. Identify Potentially Applicable Methods
A method reference expression (§15.13) is potentially compatible with a functional interface type
T
if, where the arity of the function type ofT
isn
, there exists at least one potentially applicable method when the method reference expression targets the function type with arityn
(§15.13.1), and one of the following is true:
- The method reference expression has the form
ReferenceType :: [TypeArguments] Identifier
and at least one potentially applicable method is either (i) static and supports arityn
, or (ii) not static and supports arityn-1
.
您要使用的函数类型的参数为 2
void accept(T t, U u);
并且 ArrayList::add
引用的方法的数量为 1,并且它不是静态的。这使得它具有潜在的适用性。
关于java - 为什么方法引用与具有不同参数数量的功能接口(interface)兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57828856/