Most anonymous inner classes are really closures at heart, the same way inversion of control is really monadic handling at heart.
Groovy, recognizing this synchronicity, allows you to coerce a closure into an interface implementation via the as keyword. For instance:
// Groovy way of expressing the natural comparator def c = {a,b -> a <=> b} as Comparator
Interfaces with multiple requirements can be implemented by constructing a map of string names to closure implementations, and then coercing the map via the as keyword.
So there’s really no need for anonymous inner classes. They’re theoretically coming in Groovy 1.7 in order to appease the Groovy-as-superset-of-Java sales pitch, but I wish Groovy would stick to its guns — the coercion is a lot nicer, and reveals what’s actually going on in the code: a function or two is being defined and passed around.
(Since it was noted that there’s no Google hook for this trick, I’ve decided to share it in the hopes that it will be picked up. “Anonymous inner class” or “inner class” for “Groovy” and “Grails” should really link to this stunt.)
Related posts:
Pingback: David R. MacIver » Blog Archive » We don’t need anonymous inner classes? Bollocks to that.