在Java 8中,方法可以创建为Lambda表达式,并且可以通过引用传递(通过一些工作).有大量的在线示例,lambdas被创建并与方法一起使用,但没有关于如何使用lambda作为参数的方法的示例.那是什么语法?
MyClass.method((a, b) -> a+b);
class MyClass{
//How do I define this method?
static int method(Lambda l){
return l(5, 10);
}
}
Run Code Online (Sandbox Code Playgroud) 假设我在Java 8中有以下功能接口:
interface Action<T, U> {
U execute(T t);
}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,我需要一个没有参数或返回类型的操作.所以我写这样的东西:
Action<Void, Void> a = () -> { System.out.println("Do nothing!"); };
Run Code Online (Sandbox Code Playgroud)
但是,它给了我编译错误,我需要把它写成
Action<Void, Void> a = (Void v) -> { System.out.println("Do nothing!"); return null;};
Run Code Online (Sandbox Code Playgroud)
这很难看.有没有办法摆脱Void类型参数?