callback
* copied from Mailing List
callback creates a wrapper function around another function, automatically inserting arguments into the original function that will persist every time the wrapper function is called.
It can be used like :
public function foo(x:Int, y:Int) {return x+y;} public static function main(){ // creates a copy of foo() that automatically makes the first argument a 4 var foo_cb = callback(foo,4); trace(foo_cb(5)); // traces 9 }
The question that keeps coming up is… why would anyone want to do this?
It seems similar to what you can accomplish through some of the methods in Reflect.callMethod(). Callback also seems more limited than any of the Reflect methods. You can only insert arguments in order (i.e. you must specify the first argument before you can specify the second argument, and so forth). So, you can't really use it to only specify the final argument of a method.
The big feature of using callback is that it is a fully typed call, for both arguments and arity, so you get type-safe code (vs. Reflect). The main benefit of callback (for me anyways) comes inside of functional routine arguments, such as the Lambda methods. The Lambda method arguments typically require the form f: A->B, so they accept only a single argument.
With callback, you can quickly create wrapper functions that save you the trouble of writing out one-off function blocks. Consider the following two snippets:
// calculate the following powers of 3 trace(Lambda.map( [10,2,36,4,5], callback(Math.pow, 3)));
vs.
trace(Lambda.map( [10,2,36,4,5], function(x) { return Math.pow(3,x);}));
So, it saves a few keystrokes, is type-safe, and isn't horribly difficult to parse (visually). For some reason, I really dislike inserting function blocks into method arguments. Callback gets rid of several of these instances, so I use it. But other than that it's a pretty minor tool.