Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

Java 1.5 introduced Generics. Using generics you can write code that can be statically checked to a greater degree at compile time. In some ways this is at odds with the emphasis of dynamic languages where in general, the type of objects can not be determined until runtime. But Groovy aims to accomodate Java's static typing when possible, hence Groovy 1.5 now also understands Generics. Having said that, Groovy's generics support doesn't aim to be a complete clone of Java's generics. Instead, Groovy aims to allow generics at the source code level (to aid cut and pasting from Java) and also where it makes sense to allow good integration between Groovy and Java tools and APIs that use generics.

You can include generics in your definitions like this:

Code Block
import java.lang.reflect.Method
Iterable<Method> methods = String.methods.grep{'get') }
assert == [ "getBytes", "getBytes", "getBytes", "getBytes", "getChars", "getClass" ]

Implementation note: Java's generics implementation incorporates a feature known as "type erasure" which "throws away" generic type information after completing static type checking. This allows Java to easily integrate with legacy "non-generics" libraries. Groovy currently does a little further and throws away generics information "at the source level". Generics information is kept within signatures where appropriate (see for example the method foo below within class D).

You can define classes using generics like this:

Code Block
class A extends ArrayList<Long> {}

class B<T> extends HashMap<T,List<T>> {}

class C<Y,T extends Map<String,Map<Y,Integer>>> {}

class D {
    static < T > T foo(T t) {return null}