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,
) 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.
Related Posts:
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
Very cool, just did a quick search on [Krugle](http://www.krugle.org/kse/files?query=astype&lang=groovy) (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.