我想声明一个函数,该函数接受3个参数并返回一个自定义对象,如下所示

public static returnResult leadRatingFunction(LeadMaster lead,JSONObject json,String str)
{

}
// Where returnResult and LeadMaster are custom objects

我已经在功能接口(interface)中声明了此功能,如下所示:
@SuppressWarnings("hiding")
@FunctionalInterface

interface Function<LeadMaster,JSONObject,String,returnResult>
{
    public returnResult apply(LeadMaster lead,JSONObject jsonObject,String str);
}

我想使用此函数作为像这样的哈希映射值,
 Map<String, Function<LeadMaster,JSONObject,String,returnResult>> commands = new HashMap<>();
         commands.put("leadRating",res -> leadRatingFunction(input1 ,input2 ,input3) ) ;

但这给出了错误,因为“Lambda表达式的签名与功能接口(interface)方法apply(LeadMaster,JSONObject,String)的签名不匹配”

谢谢

最佳答案

Function<LeadMaster,JSONObject,String,returnResult>匹配的lambda表达式将需要三个参数:

Map<String, Function<LeadMaster,JSONObject,String,returnResult>> commands = new HashMap<>();
commands.put("leadRating",(a,b,c) -> leadRatingFunction(a,b,c));

另外,如Lino所述,您可以使用方法引用:
commands.put("leadRating",YourClass::leadRatingFunction);

顺便说一句,我不确定您是否希望Function<LeadMaster,JSONObject,String,returnResult>接口(interface)是通用的,因为您将实际类的名称放置为通用类型参数。

如果需要通用参数,请使用通用名称:
interface Function<A,B,C,D>
{
    public D apply(A a ,B b , C c);
}

否则,它不必是通用的:
interface Function
{
    public returnResult apply(LeadMaster lead,JSONObject jsonObject,String str);
}

关于java - Lambda表达式的签名与功能接口(interface)方法的签名不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47015321/

10-11 02:26