function filter(list, predicate){ @filteredList = [];for-each (@x in list) if (predicate(x)) filteredList.add(x);return filteredList;}
//filter for even numbersfilter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)});
Function<Integer,Integer> lambda = t -> {int n = 2return t * n}
Closures hold state because it uses external variables (i.e. variable defined outside the scope of the function body) along with parameters and constants to perform operations.
int n = 2
Function<Integer,Integer> closure = t -> {return t * n}
When Java creates closure, it keeps the variable n with the function so it can be referenced when passed to other functions or used anywhere.
void register_func(void(*f)(int val)) // Works only with an EMPTY capture list{int val = 3;f(val);}
int main(){int env = 5;register_func( [](int val){ /* lambda body can access only val variable*/ } );}
一旦在捕获列表([env])中引入了来自周围环境的自由变量,就必须生成闭包。
register_func( [env](int val){ /* lambda body can access val and env variables*/ } );
由于这不再是一个普通的函数,而是一个闭包,因此会产生编译错误。 no suitable conversion function from "lambda []void (int val)->void" to "void (*)(int val)" exists