我目前开始学习 Java 中的 Lambda 表达式,我试图找出为什么这段代码不起作用 我有一个普通类:
import java.util.function.ToIntBiFunction;
public class testclass {
public testclass() {
}
public static ToIntBiFunction<Integer,Integer> multit2 = (Integer a,Integer b)->{
return a*b;
};
public static Integer multit(Integer a, Integer b) {
return a*b;
}
}
以及另一个类中的main
public class ImageCovertor{
public static void main (String[] args) throws IOException {
int d;
testclass test = new testclass();
BiFunction<ToIntBiFunction,Integer, Integer> ddd = (ToIntBiFunction fn, Integer a)->{
return fn.applyAsInt(a,a);
};
d= ddd.apply(testclass::multit, 5);
System.out.println(d);
}//end of main
public static ToIntBiFunction<Integer,Integer> multit = (Integer a,Integer b)->{
return a*b;
};
}
我正在尝试将 multit 作为 ddd lambda 函数中的参数传递 但是这样的代码给了我一个错误:
d= ddd.apply(testclass::multit, 5);
类型 testclass 没有定义适用于此的 multit(Object, Object)
也尝试在主函数中创建该函数,但它给了我同样的错误 当我编写代码时,代码可以工作
testclass.multit
而不是
testclass::multit
有人可以向我解释为什么第二个不起作用以及如何解决这个问题吗? 谢谢
最佳答案
testclass::multit
表示属于 testclass
的方法 multit
。您拥有的是一个包含函数的字段 testclass.multit
。保存函数的字段与方法不同。
class MyClass {
// This is a method, `MyClass::foo`
public static Integer foo(Integer a, Integer b) {
return a*b;
}
// This is a field holding a function, `MyClass.bar`
public static ToIntBiFunction<Integer, Integer> bar = (Integer a,Integer b)-> {
return a*b;
};
}
关于java - 无法将 ToIntBiFunction 作为 java lambda 表达式中的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50299328/