Lambda表达式的签名与应用的功能接口方法的签名不匹配

AJN*_*AJN 3 java lambda java-8

我想声明一个接受3个参数的函数,并像这样返回一个自定义对象

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

}
// Where returnResult and LeadMaster are custom objects 
Run Code Online (Sandbox Code Playgroud)

我在功能界面中声明了这个功能如下,

@SuppressWarnings("hiding")
@FunctionalInterface

interface Function<LeadMaster,JSONObject,String,returnResult>
{
    public returnResult apply(LeadMaster lead,JSONObject jsonObject,String str);
}
Run Code Online (Sandbox Code Playgroud)

我想将此函数用作这样的哈希映射值,

 Map<String, Function<LeadMaster,JSONObject,String,returnResult>> commands = new HashMap<>();
         commands.put("leadRating",res -> leadRatingFunction(input1 ,input2 ,input3) ) ;
Run Code Online (Sandbox Code Playgroud)

但它给出了错误,因为"Lambda表达式的签名与应用的功能接口方法的签名不匹配(LeadMaster,JSONObject,String)"

谢谢

Era*_*ran 9

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

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

或者,正如Lino所评论的那样,您可以使用方法参考:

commands.put("leadRating",YourClass::leadRatingFunction);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我不确定您希望您的Function<LeadMaster,JSONObject,String,returnResult>接口是通用的,因为您将实际类的名称作为泛型类型参数.

如果需要通用参数,请使用通用名称:

interface Function<A,B,C,D>
{
    public D apply(A a ,B b , C c);
}
Run Code Online (Sandbox Code Playgroud)

否则,它不必是通用的:

interface Function
{
    public returnResult apply(LeadMaster lead,JSONObject jsonObject,String str);
}
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`SomeClass :: leadRatingFunction` (3认同)