Can someone explain Anonymous methods to me?

Steve picture Steve · Nov 1, 2008 · Viewed 8.3k times · Source

Delphi 2009, among some cool stuff, has also just got Anonymous methods. I've seen the examples, and the blog posts regarding anonymous methods, but I don't get them yet. Can someone explain why I should be excited?

Answer

Toon Krijthe picture Toon Krijthe · Nov 1, 2008

Please have a look at closures.

Delphi anonymous functions are closures.

These are created within other functions and as such has access to the scope of that function. This is even so if the anonumous function is assigned to a function parameter that is called after the original function is called. (I will create an example in a moment).

type
  TAnonFunc = reference to procedure;
  TForm2 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    F1 : TAnonFunc;
    F2 : TAnonFunc;
  end;

procedure TForm2.Button1Click(Sender: TObject);
var
  a : Integer;
begin
  a := 1;

  F1 := procedure
  begin
    a := a + 1;
  end;

  F2 := procedure
  begin
    Memo1.Lines.Add(IntToStr(a));
  end;
end;

The above method assigns two anonymous functions to the fields F1 and F2. The first increases the local variable and the second showe the value of the variable.

procedure TForm2.Button2Click(Sender: TObject);
begin
  F1;
end;

procedure TForm2.Button3Click(Sender: TObject);
begin
  F2;
end;

You can now call both functions, and they access the same a. So calling F1 twice and F2 once shows a 3. Of course this is a simple example. But it can be expanded to more usefull code.

In the multi threading environment, anonymous functions can be used in a call to Synchronise, which eliminates the need for countless methods.