Overriding the 'as' operator 2

Posted by Warner Onstine Thu, 06 Dec 2007 16:40:25 GMT

A friend of mine sent me a link to Charles Nutter’s blog on implementing interfaces using the as operator. While I was explaining how it worked to him I remembered that like many operators you can also override this one using asType(). This got us to thinking when would you use this functionality?

I have one project I’m working on right now (not ready to talk yet about as I want more code in place before I unveil it, :-P) but this might be useful. Say that you wanted to duck-type your object for specific class instances. Overriding as may be one place to do it.

When would this make sense? Personally I think something like this makes the most sense in a library that provides some kind of functionality to a bunch of classes (rather than a one-off case). But I’m curious to see how others have used this functionality, would help to shed some light on other uses I hadn’t thought of.

Trackbacks

Use the following link to trackback from your own site:
http://www.warneronstine.com/blog/articles/trackback/307

Comments

Leave a response

  1. Andres Almiray about 15 hours later:

    Well for my part I use it on Json-lib to transform Strings, Lists and Maps to their JSON representation with a single coercion with as

    http://json-lib.sourceforge.net/groovy.html

  2. Warner Onstine 1 day later:

    Very cool, just did a quick search on Krugle (yours is the only one that showed up).

    So, what you're doing is creating three metaclasses for ArrayList, HashMap and String and then overriding the asType call through invokeMethod. Pretty slick.

Comments