Advanced Enhancements

add to Add to Blinkslist add to furl Digg it add to ma.gnolia Stumble It! add to simpy seed the vine TailRank post to facebook
In Keef’s post pointing out some problems with generics in java, he made a quick mention of enhancements of generic types. It’s an interesting feature of enhancements in GScript so I thought people would enjoy a more in depth explanation.

Often you want methods associated with a particular parameterization of a class. This is especially true of Collections. A canonical example is that, rather than typing:

  Collections.sort( myListOfComparables )

You would rather type:


The rub is that sort() only makes sense for Lists of Comparable objects. It makes sense on a List<String>, but not on List<Object>. You can imagine other methods that are sensitive to the type of values that a Collection holds: min() and max() on Collections of Comparables, sum() on Collections of numbers, etc.

It turns out that GScript Enhancements let you put these methods where they belong. As an example, here is a simple definition of that sort() method:

enhancement GWBaseListOfComparablesEnhancement<T extends Comparable>
                    : List<T>
  function sort() : List<T>{
    Collections.sort( this )
    return this

NOTE: sorry I had to wrap the enhancement definition. The : List<T> would normally be on the same line as the enhancement’s definition

So what is this saying? We are defining an enhancement that applies to all Lists of T, where T is bounded by the extends Comparable clause. The sort() method simply passes the enhanced object through to java’s standard Collections.sort() method. This type checks because we know T extends Comparable.

With that enhancement defined, any list that is parameterized on a Comparable class will have a sort() method on it. Everything is nice and type-safe.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s