Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Declaring Generics



Groovy is a dynamically typed language, but we can still use generics in the same way as in Java to allow interoperatbility and have more fine grain control over type constraint.

Declaring a Generic Class

In case, we need to define a class which can work with different type of data, we can introduce type parameters during class declaration.

Syntax

class GenericList <T> {}

Here T declare the type that this class is intended to hold and perform actions accordingly. Consider the following example −

Example.groovy

class GenericList <T> {
    T item
    
    GenericList(T item) {
        this.item = item
    }
}

// Using Generic Class for Integers
def integerList = new GenericList<Integer>(10)
// prints 10
println integerList.getItem() 

// Using Generic Class for Strings
def stringList = new GenericList<String>("ABC")
// prints ABC
println stringList.getItem()

Output

When we run the above program, we will get the following result.

10155

Here GenericList is a generic class which can accept any type as T. When we're creating a instance of GenericList, we specify the required type using angular brackets for example new GenericList<Integer>.

Declaring a Generic Method

We can declare a Generic Method in a non-generic class as well as shown in example below −

Example.groovy

class Utility {
   static <E> List<E> getList(E... elements) {
      return new ArrayList<E>(Arrays.asList(elements))
   }
}

// get list of numbers
def numbers = Utility.getList(1, 2, 3, 4)
// prints [1, 2, 3, 4]
println numbers

// get list of strings
def words = Utility.getList("apple", "banana", "mango")
// prints [apple, banana, mango]
println words

Output

When we run the above program, we will get the following result.

[1, 2, 3, 4]
[apple, banana, mango]

Here <E> signifies the type that getList() method is handling making it a generic method. Groovy infers the type of E by the type of arguments passed to the generic method.

Advertisements