2 min read

Feature fiction: Generics in Apex

Feature fiction: Generics in Apex
Photo by Jan Huber / Unsplash

As of the Winter'23 release, Apex does not support generics (yet).

Generics are a way to build classes and methods around a placeholder type. There are already generics in Apex, and you use them every time you code. The collections List<T>, Set<T> and Map<T1,T2> are generic types that become constructed types when we specify a type in the parameters (e.g. List<Integer>, Set<Id>, Map<Id, Account>). The variables T, T1, T2 are the type parameters of the generic types. While the presence of generics in Apex is not new, it would be new if we were given the ability to define new custom generics.

Generics would be particularly useful if we wanted to craft some sort of custom collection. The following conceptual code, which does not work at the time of writing this, could be an example of how we could use Apex to build a stack using generics:

public class Stack<T> {
	
    private List<T> stack = new List<T>();
    
    public void push(T element) {
    	stack.add(element);
    }
    
    public T pop() {
    	return stack.remove(stack.size() - 1);
    }
}

Stack<Integer> theStack = new Stack<Integer>();

theStack.push(1);
theStack.push(2);
theStack.push(3);

Assert.equals(3, theStack.pop());

The key benefit from using generics is code economy, keeping the codebase dry. It could also significantly simplify the code around type-heavy operations like JSON parsing.

Generics become more powerful when we can specify constraints on the types that can be applied to. For instance, we would want to restrict the valid types to those that implement a given interface (e.g. Comparable, Equatable), or to those explicitly included in a closed list (e.g. only Tasks and Events), to guarantee that a certain method will be available for the generic type.

We should highlight that without the ability to extend existing primitives and SObject definitions to conform to certain interfaces (like in Swift), the ability to filter by interface would be limited to custom non-SObject classes.

If you want to learn more about how other languages solve for generics, you can take a look at the documentation for C# and Swift (note that Swift protocols are similar to interfaces).