Zif*_*fre 27
不幸的是,在Java 8引入Lambda Expressions之前,Java中没有lambda .但是,您可以使用匿名类获得几乎相同的效果(以非常难看的方式):
interface MyLambda {
void theFunc(); // here we define the interface for the function
}
public class Something {
static void execute(MyLambda l) {
l.theFunc(); // this class just wants to use the lambda for something
}
}
public class Test {
static void main(String[] args) {
Something.execute(new MyLambda() { // here we create an anonymous class
void theFunc() { // implementing MyLambda
System.out.println("Hello world!");
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
显然这些必须在单独的文件中:(
我不认为有一个确切的等价物,但是有一些匿名类可以尽可能接近.但仍然非常不同.乔尔·斯波尔斯基(Joel Spolsky)写了一篇文章,讲述了学生如何只教Java,他们错过了这些函数式编程的优点:你的编程语言可以做到吗?.