在functional programming 里面常常说起closure 闭包。 那么究竟闭包是一个什么东东? 让人如何难以理解呢?
java
1 闭包定义闭包
closure is an instance of a function that can reference nonlocal variables of thatide
function with no restrictions。这是闭包的英文定义。说实在这段定义确实很抽象让人难以理解。函数
而后我这里其实有两个点把这段定义具体化:spa
1.1。 闭包就是容许做为参数被传递到另一个函数。rest
1.2。 闭包容许访问(access)修改(modify)闭包的外部变量。it
2根据上面两点,这里经过代码来讲明什么是闭包。io
PS: 这里我不但愿详细解释闭包的更深层内容,可是经过列举代码来讲明java8 部分支持闭包。( java 8 不支持修改外部变量)java8
List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); //closure could be assigned to another method //这里说明闭包能够做为一个变量 Predicate<String> 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");*/