在functional programming 里面经常提及closure 闭包。 那么究竟闭包是一个什么东东? 让人如何难以理解呢?
1 闭包定义
closure is an instance of a function that can reference nonlocal variables of that
function with no restrictions。这是闭包的英文定义。说实在这段定义确实很抽象让人难以理解。
然后我这里其实有两个点把这段定义具体化:
1.1。 闭包就是允许作为参数被传递到另外一个函数。
1.2。 闭包允许访问(access)修改(modify)闭包的外部变量。
2根据上面两点,这里通过代码来说明什么是闭包。
PS: 这里我不希望详细解释闭包的更深层内容,但是通过列举代码来说明java8 部分支持闭包。( java 8 不支持修改外部变量)List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
//closure could be assigned to another method
//这里说明闭包可以作为一个变量
Predicate predicate = (s) -> "a".equals(s);
list.stream().filter(predicate);
//closure could be access outer var
//闭包里面可以访问外部变量
final String outerStr = "Outer";
list.forEach(s -> System.out.println(outerStr+s));
//由于java的匿名内部类只允许变量为final,所以这里不支持在闭包里面修改
//变量outerStr2
//in java closure can't modify outer variable can't not compile
/*String outerStr2 = "Outer";
list.forEach(s -> outerStr2 = "modifyOuter");*/