Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Units and Object Pascal

Generics and Anonymous Methods

Write type-safe generic classes like TList of T, add constraints, and use anonymous methods and closures in modern Delphi and Free Pascal, with a runnable C stand-in.

Two features changed how Object Pascal code looks after 2009: generics (one piece of code that works for many types) and anonymous methods (small unnamed routines you can pass around, which remember the variables around them). Both are standard in current Delphi. Free Pascal has generics too, with slightly different syntax rules in its default mode, and supports anonymous functions in newer versions.

This lesson shows the Delphi forms, which you will meet in nearly every modern code base.

Why generics exist

Before generics, a list of integers and a list of strings needed either two copies of the code or a list of TObject that you cast on the way out, and the compiler could not catch a wrong cast. A generic type has a type parameter in angle brackets. The compiler produces a checked version for each type you use.

PASCAL
uses
  System.Generics.Collections;

var
  Names: TList<string>;
  Scores: TDictionary<string, Integer>;
begin
  Names := TList<string>.Create;
  try
    Names.Add('Ada');
    Names.Add('Grace');
    // Names.Add(42);   // compile error: 42 is not a string
    WriteLn(Names.Count);   // 2
  finally
    Names.Free;
  end;
end;

TList<T>, TDictionary<K,V>, TObjectList<T>, TStack<T> and TQueue<T> all live in System.Generics.Collections and are the everyday containers of Delphi. (Free Pascal's equivalents are in Generics.Collections.)

Writing your own generic class

You declare a type parameter after the class name. Inside the class, T stands for any type:

PASCAL
type
  TBox<T> = class
  private
    FValue: T;
    FHasValue: Boolean;
  public
    procedure Put(const AValue: T);
    function Get: T;
    function HasValue: Boolean;
  end;

procedure TBox<T>.Put(const AValue: T);
begin
  FValue := AValue;
  FHasValue := True;
end;

function TBox<T>.Get: T;
begin
  if not FHasValue then
    raise Exception.Create('Box is empty');
  Result := FValue;
end;

function TBox<T>.HasValue: Boolean;
begin
  Result := FHasValue;
end;

Using it looks like using TList<string>: TBox<Integer>.Create, TBox<TDateTime>.Create. Each distinct type argument produces its own specialized class. This is also available for records, interfaces and routines (a generic method such as function Max<T>(A, B: T): T).

Constraints

Sometimes the generic code needs to know something about T. A constraint restricts the types allowed:

PASCAL
type
  TRegistry<T: class, constructor> = class
  public
    function MakeOne: T;
  end;

function TRegistry<T>.MakeOne: T;
begin
  Result := T.Create;     // allowed: T is a class with a parameterless constructor
end;

The usual constraints are class (a class type), record (a value type), constructor (has a public parameterless Create) and a named class or interface, as in T: TShape or T: IComparable. Constraints turn an error deep inside generic code into a clear message at the line that picks a wrong type.

Anonymous methods

An anonymous method is a routine without a name, written where you need it. Its type is declared with reference to:

PASCAL
type
  TTransform = reference to function(X: Integer): Integer;

function ApplyTwice(F: TTransform; V: Integer): Integer;
begin
  Result := F(F(V));
end;

begin
  WriteLn(ApplyTwice(function(X: Integer): Integer
                     begin
                       Result := X * 3;
                     end, 5));          // 45
end.

The RTL already declares common types: TProc (no parameters), TProc<T>, TFunc<TResult>, TFunc<T, TResult> and TPredicate<T>. You can use them instead of writing your own.

Closures: capturing variables

An anonymous method can use variables of the routine around it. It keeps them alive after that routine returns. This is a closure:

PASCAL
function MakeCounter: TFunc<Integer>;
var
  N: Integer;
begin
  N := 0;
  Result := function: Integer
            begin
              Inc(N);
              Result := N;
            end;
end;

var
  Next: TFunc<Integer>;
begin
  Next := MakeCounter;
  WriteLn(Next());   // 1
  WriteLn(Next());   // 2
end.

N is a local variable of MakeCounter, yet each call of Next still sees and changes it. Behind the scenes the compiler moves N into a hidden reference-counted object.

Delphi captures variables, not values. If you create several closures in a loop and they all use the loop variable, they share one variable. Copy the value into a fresh local inside the loop to capture each separately.

The C stand-in below builds the same two ideas by hand. A macro makes a stack for any type (the generic part). A closure is a pair of a function pointer and a pointer to its captured variable (the anonymous method part).

C Stand-in: a generic stack and a closure in C

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Each counter keeps its own hidden state, which is exactly what the compiler arranges for a Delphi closure.

Practical advice

  • Use the standard generic containers instead of writing your own lists.
  • Prefer TObjectList<T> when the list should own and free its objects (set OwnsObjects, which is the default).
  • Anonymous methods are great for callbacks, sorting comparers (TComparer<T>.Construct(...)) and TThread.Queue, but do not capture a form or component that might be destroyed before the closure runs.
  • Generic code is compiled per type, so a large generic class used with many types makes the executable bigger.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does TList<string> give you over an untyped list of TObject?

    The type parameter makes the list type safe: a wrong type is a compile-time error.
  2. 2. What does the constraint T: class, constructor allow inside generic code?

    constructor guarantees a public parameterless Create, and class guarantees T is a class type.
  3. 3. An anonymous method uses a local variable of its enclosing routine. What happens when that routine returns?

    That is a closure: captured variables are moved into a reference-counted hidden object that lives as long as the method reference does.
  4. 4. Which type declares an anonymous method type taking an Integer and returning an Integer?

    TFunc<T, TResult> is a reference to function(Arg: T): TResult.

Summary

  • Generics let one class or routine work for many types while the compiler checks the types.
  • Constraints (class, record, constructor, a named type) say what T must support.
  • reference to declares an anonymous method type; TProc, TFunc and TPredicate cover most needs.
  • Closures capture variables, not values, and keep them alive.
  • Generic containers in System.Generics.Collections are the standard collections.

Next: Classes and Objects