Delphi. Lambda. Anonymous methods

Example

program LambdaExamples;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  TSayHello = reference to function(aName: string): string;

  TFuncOfIntToString = reference to function(x: Integer): string;

  TFuncOfString = reference to function(a, b: string): string;

  TMethodReference = reference to procedure(aArg: string);

  TSomeClass = class
    procedure Foo(aArg: string);
  end;

var
  myFunc: TFuncOfIntToString;
  concater: TFuncOfString;
  someClassInstance: TSomeClass;
  m: TMethodReference;
  sayHello: TSayHello;


// lets say we have following functions
procedure AnalyzeProcedure(func: TFuncOfIntToString);
begin
  // use argument
  WriteLn(func(12));
end;

function MakeConcat(y: Integer): TFuncOfString;
begin
  Result :=
    function(a, b: string): string
    begin
      Result := Format('%s %s %s', [a, b, y.ToString()]);
    end;
end;

{ TSomeClass }

procedure TSomeClass.Foo(aArg: string);
begin
  Writeln(aArg);
end;

begin

   // 1. lets say we in context of some class and we need to do
   // smth fast without overhead of instantiate new class
   // we can do it like this
  sayHello :=
    function(aName: string): string
    begin
      Result := Format('hello %s', [aName]);
    end;
  WriteLn(sayHello('Stan'));

  //2.  use lambda directly in another function
  AnalyzeProcedure(
    function(x: Integer): string
    begin
      Result := IntToStr(x);
    end);

  //3.  put lambda to variable
  myFunc :=
    function(x: Integer): string
    begin
      Result := IntToStr(x);
    end;

  AnalyzeProcedure(myFunc);

  //4.  --- Closure
  concater := MakeConcat(123);
  WriteLn(concater('a', 'b'));

  //5.  reference to method
  someClassInstance := TSomeClass.Create();
  try
    m := someClassInstance.Foo;
    m('this is reference to method');

    // ACHTUNG !!! DONT' DO LIKE THIS
    // someClassInstance.Foo := m;  << DANGER OF MEMORY LEAKS
  finally
    someClassInstance.Free();
  end;

  ReadLn;
end.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.