Justin du Coeur (jducoeur) wrote,
Justin du Coeur

Let us sing the praises of the Actionscript Class class

Since I'm language-geeking today anyway, let me be even-handed about it. It turns out that, while Actionscript (the language that underlies Flash) has been trying to look more and more like plain old statically-typed Java, it still has some fine dynamic goodness hidden under the covers.

Today's lesson comes out of this code snippet:
public function sendIQ(extClazz:Class, cb:Function):void {
   var iq:IQ = new IQ(serviceJid, IQ.GET_TYPE, null, null, null, 
      function (iq:IQ):void {
         var reply:Object = iq.getAllExtensionsByNS(extClazz.fullNS)[0];
   iq.addExtension(new extClazz());
public function sendTestMessage():void {
      function(reply:UserInfoExtension):void {
         Alert.show("And I am still " + reply.userName);
This is the experiment that I really hadn't expected to work, alluded to in my previous post. Without getting too much into the details (suffice it to say, I'm starting to get my XMPP client together), the sendIQ() function sends an IQ (an Information Query) to the server, and handles it when it comes back. sendIQ() takes a Class (the extClazz parameter), and without any reflection complexity, it calls both a constructor on that Class object ("new extClazz()") and a static method on it ("extClazz.fullNS"). Despite the fact that the class being passed in is nominally statically typed, the language allows me to *use* it in some dynamic ways without hassle. The only thing I couldn't do was actually use it as a type signature: trying "var reply:extClazz" just didn't work, but that's okay, since it recasts it and dynamically type-checks it when it gets passed into the callback cb.

So I'm pleased and impressed: I've *never* seen Actionscript used this way, and I'm quite happy to see that it works. This pattern is going to save me lots of boilerplate while writing the ConvYou client -- the sendTestMessage() method shows what a typical query to the server will look like, nice and lean. I still prefer Scala's type system, which allows me to do the above sort of thing while remaining statically typed end-to-end, but this is entirely practical and usable. (But boy, I am ever gladder that I'm escaping the Java coal mines...)
Tags: programming
  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded