An anonymous method is used to 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.
Anonymous methods start with the
method keyword, followed by a Method signature and a
end block that includes one or more Statements.
Anonymous methods can use any member defined in the scope they are defined in. Any change done to variables 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 var b := 10; Loop(method(a: Integer); begin writeLn(a+) end); end;
An alternative syntax for defining anonymous methods is a Lambda expression, which is shorter but cannot provide parameter types and relies on type inference.
Static Anonymous Methods
Anonymous methods may optionally be declared as static, by prefixing them with the
class keyword. This is works analogous to static anonymous methods in C# 9.0.
method Test; begin var b := 10; const c := 20; Loop(class method(a: Integer); begin writeLn(a+c); // cannot access "b" here. end); end;
Making anonymous methods static can avoid unintentionally or unnecessarily capturing state from the enclosing context, which could result in extra overhead.