【问题标题】:Lambda expression's signature does not match the signature of the functional interface method applyLambda 表达式的签名与功能接口方法的签名不匹配 apply
【发布时间】:2017-10-30 12:29:35
【问题描述】:

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

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

}
// Where returnResult and LeadMaster are custom objects 

我在函数式接口中声明了这个函数,如下,

@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 表达式的签名与功能接口方法 apply(LeadMaster, JSONObject, String) 的签名不匹配”而出现错误

谢谢

【问题讨论】:

  • 什么是input1 ,input2 ,input3?可能不是LeadMaster, JSONObject, String .. 编辑:等等,你到底想用那张地图做什么?
  • 我尝试使用 LeadMaster, JSONObject, String 。但它不会工作
  • 只是编辑,你想用地图做什么?你需要定义一个像(lead, json, str) -&gt; ... 这样的函数,因为这是你声明的。您可能应该看看如何使用 lambda 以及如何声明函数

标签: java lambda java-8


【解决方案1】:

匹配 Function&lt;LeadMaster,JSONObject,String,returnResult&gt; 的 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&lt;LeadMaster,JSONObject,String,returnResult&gt; 接口是通用的,因为您将实际类的名称作为通用类型参数。

如果您想要泛型参数,请使用泛型名称:

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);
}

【讨论】:

  • 或者只是SomeClass::leadRatingFunction
猜你喜欢
  • 1970-01-01
  • 2011-03-01
  • 2018-01-15
  • 2020-02-18
  • 2021-06-18
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多