什么是闭包? java有闭包吗? [英] What is a closure? Does java have closures?
问题描述
我正在阅读面向对象的Javascript,并发现了闭包的概念。我不太明白为什么和什么时候使用。其他语言如Java也有闭包?我基本上想了解如何知道闭包的概念可以帮助我改进我的编码。
I was reading Object Oriented Javascript and found the concept of closures. I didn't quite understand why and when it is used. Do other languages like Java also have closures? I basically want to understand how knowing the concept of closures can help me improve my coding.
推荐答案
闭包是一个第一类函数带有绑定变量。
A closure is a first class function with bound variables.
大致意思是:
- 闭包作为其他函数的参数
- 闭包存储在创建时存在的词汇作用域中的一些变量的值
Java最初对闭包没有句法支持(这些在Java 8中引入),尽管使用匿名内部类来模拟它们是相当常见的做法。这里有一个例子:
Java initially didn't have syntactic support for closures (these were introduced in Java 8), although it was fairly common practice to simulate them using anonymous inner classes. Here's an example:
import java.util.Arrays;
import java.util.Comparator;
public class StupidComparator {
public static void main(String[] args) {
// this is a value used (bound) by the inner class
// note that it needs to be "final"
final int numberToCompareTo=10;
// this is an inner class that acts like a closure and uses one bound value
Comparator<Integer> comp=new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
int result=0;
if (a<numberToCompareTo) result=result-1;
if (b<numberToCompareTo) result=result+1;
return result;
}
};
Integer[] array=new Integer[] {1,10, 5 , 15, 6 , 20, 21, 3, 7};
// this is a function call that takes the inner class "closure" as a parameter
Arrays.sort(array,comp);
for (int i:array) System.out.println(i);
}
}
这篇关于什么是闭包? java有闭包吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!