2 ms·
The thing is, all of these languages have adopted something like closures because they're just very useful. Creating different copies of a function with differe
by tsimionescu 3y ago
The thing is, all of these languages have adopted something like closures because they're just very useful. Creating different copies of a function with different values for each item in some local variable/collection comes up very often. Even Java actually supports it, since it does allow you to copy values from the local scope to an inner function scope, even though it doesn't allow you to capture variables. And, since this is a GC language, those values can be references to local objects that can survive after the outer scope exits if they are referenced from the inner scope.
Even in Java, this was there as part of Java 1.0, in the form of instance-scoped inner objects, in a form like this:
for(int i=0; i < arr.length(); i++) {
final int copy = i;
listeners = new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("pressed button " + copy);
}
}
}
- adrian_b 3y agoFor all such examples of using closures there are alternative implementations that use more efficient mechanisms. For examples like this, if it is not desired to use a single function with one extra parameter, then multiple functions that differ in using some different constants or different private static variables can be generated by some template mechanism, without using closures. The problem with closures is that they introduce an overhead in any function that is passed as a parameter or used for some other reason through a pointer, by adding an extra indirection, even if in most cases this is not needed, instead of adding overhead only in the few cases when capturing local variables is really useful (unless something like whole program optimization is used).