Tradicionalmente o Delphi possui a possibilidade de retornar o valor da função através do próprio nome da função, ou através da variável “Result”.
1 2 3 4 5 6 7 8 9 |
function TForm1.RetornoAtravesDeResult: String; begin Result := 'Olá mundo!'; end; function TForm1.RetornoAtravesDoProprioNome: String; begin RetornoAtravesDoProprioNome := 'Olá mundo!'; end; |
Porém, umas das novidades que saiu no Delphi 2009, mas que poucas pessoas hoje conhecem (ou pelo menos comentam), é a capacidade de retornar o valor de uma função através do comando “Exit”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } function Teste: String; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage(Self.Teste); end; function TForm1.Teste: String; begin Exit('Olá mundo!'); end; end. |
Isso é útil quando você precisa, depois de alimentar o retorno da função, chamar Exit para sair do escopo atual:
O exemplo abaixo (apenas educativo!):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function TForm1.RetornaUmValor(AValor: Integer): Integer; var I: Integer; begin //Alguma coisa feita aqui... for I := 1 to 10 do begin if AValor = 10 then begin Result := AValor; Exit; end; end; //Continua a fazer alguma coisa aqui... end; |
Pode ser simplificado assim:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function TForm1.RetornaUmValor(AValor: Integer): Integer; var I: Integer; begin //Alguma coisa feita aqui... for I := 1 to 10 do begin if AValor = 10 then begin Exit(AValor); end; end; //Continua a fazer alguma coisa aqui... end; |
Até a próxima!