views:

765

answers:

2

Is there any way to have a look at signatures of anonymous functions in ActionScript 3 during runtime?

I would like to validate Function objects passed in as arguments to other functions and make sure that they accept the correct number of arguments (with the correct types) and return a value of the correct type.

flash.utils.describeType() doesn't seem to return this info for anonymous functions.

+1  A: 

As a rough approximation you can check the number of parameters using length property, e.g.:

function doStuff(callback:Function) {
  trace(callback.length);
}

I'm not aware of any way to enumerate the arguments of an anonymous functions; you can of course validate ex-post catching ArgumentError.

Luca Tettamanti
Thanks -- now that I think about it, it's not really a problem if I don't validate the function and instead just let the call throw an ArgumentException if the signature is invalid since that's probably what I would do anyway :)
hasseg
+1  A: 

It doesn't look like the runtime allows you to reflect on anonymous functions, which is a shame.

Anonymous functions are (perhaps by definition) marked as dynamic. If you pass an incompatible type into an anonymous function, no error is thrown. Any type mismatches will be silently cast as best they can. Passing something like "minotaur" as a uint parameter will yield 0 (zero), for example.

If you REALLY want to over-engineer it, you could get all OO on it. Instead of accepting anonymous functions, you could declare an interface which contains the appropriate function signature, and accept objects that implement that interface.

public interface IFancyCallback {
  public function fancyFunction(frog:Frog, princess:Girl):UsefulReturnType;
}

And your function would just have to be packaged up in an object:

public class ConcreteCallback implements IFancyCallback {
  public function fancyFunction(frog:Utensil, princess:Girl):UsefulReturnType {
    princess.kiss(frog);
    return new UsefulReturnType("jabberwocky");
  }
}

Could have the potential to create a lot of code overhead. Depends how many callbacks you intend to have, who's going to be making them, and what how serious it would be if the anon function's signature was incorrect.

Can you share any more about the problem you're trying to solve?

aaaidan
Thanks for the answer -- I had no idea no errors would be thrown if you try to pass in arguments of the wrong types.
hasseg