Overriding the ‘as’ operator 2

Posted by Warner Onstine on December 06, 2007

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.

Share and Enjoy:
  • Print
  • Digg
  • Reddit
  • del.icio.us
  • Twitter
  • Facebook
  • Google Bookmarks
  • DZone
Related Posts:
Trackbacks

Trackbacks are closed.

Comments

Comments are closed.

  1. Andres Almiray Fri, 07 Dec 2007 00:29:32 GMT+6

    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 Fri, 07 Dec 2007 15:28:20 GMT+6

    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.

blog comments powered by Disqus

Easy AdSense by Unreal