Lambda

A lambda expression is a short version of an Anonymous Method.

It is used to define an inline callbacks that is assignable to a Blocks, an interface reference with a single method that can act as a delegate, or an Expression tree.

Lambdas start with an identifier or a comma seperated list of identifiers surrounded by parenthesis, followed by the lambda operator >. After the operator, either a single expression or a begin/end block that includes one or more Statements.

The identifiers before the -> operator define the parameter names of the lambda. These have to match the number of parameters expected by the block or interface that the lambda is being assigned to, and their type will be inferred.

Lambdas, like Anonymous Method, have full access to everything available in the scope they are defined in, including type members, as well as any local Variables, Properties, Contants or other local methods declared before it.

Any change done to variables or properties in the local scope will affect the lambda, and vice versa.

method Loop(aAction: block(aValue: Integer));
begin
  for i: Integer := 0 to 10 do
    aAction(i);
end;

method Test;
begin
  Loop(a -> writeLn(a)); // This prints "0" thru "10"
end;

When there is no parameter for the lambda, an optional set of empty parenthesis or just a -> operator is allowed to start the lambda. When there is more than one parameter, parenthesis are required:

Test1( -> writeLn('test!'));       // parenthesis are optional, without parameters
Test1( () -> writeLn('test!'));

Test2( a -> writeLn($'Got {a}'));   // parenthesis are optional, for a single parameter
Test2( (a) -> writeLn($'Got {a}'));

Test3( (a,b) -> writeLn($'Got {a} and {b}')); // parenthesis are required

See Also