Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi default value for procedure parameter

Tags:

delphi

procedure CaseListMyShares(search: String);

I have a procedure like this. Here is content :

procedure TFormMain.CaseListMyShares(search: String);
var
  i: Integer;
begin
  myShares := obAkasShareApiAdapter.UserShares('1', search, '', '');
  MySharesGrid.RowCount:= Length(myShares) +1;
  MySharesGrid.AddCheckBoxColumn(0, false);
  MySharesGrid.AutoFitColumns;

  for i := 0 to Length(myShares) -1 do
  begin
    MySharesGrid.Cells[1, i+1]:= myShares[i].patientCase;
    MySharesGrid.Cells[2, i+1]:= myShares[i].sharedUser;
    MySharesGrid.Cells[3, i+1]:= myShares[i].creationDate;
    MySharesGrid.Cells[4, i+1]:= statusText[StrToInt(myShares[i].situation) -1];
    MySharesGrid.Cells[5, i+1]:= '';
    MySharesGrid.Cells[6, i+1]:= '';
  end;
end;

I want to call this function in two ways which are without any parameter and with a parameter. I found overload keyword for procedures but i dont want to write same function two times.

If i call this procedure like CaseListMyShares('');, it works.

But can i do below this in delphi ?

procedure TFormMain.CaseListMyShares(search = '': String);

and call:

CaseListMyShares();
like image 792
Nevermore Avatar asked Dec 13 '17 07:12

Nevermore


Video Answer


1 Answers

There are two ways to achieve this. Both methods are useful, and they are often interchangeable. However there are scenarios where one or other is preferable, so it is worth knowing both of the techniques below.

Default parameter value

The syntax for this is as follows:

procedure DoSomething(Param: string = '');

You can call the method like this:

DoSomething();
DoSomething('');

Both of the above behave in the same way. Indeed when the compiler encounters DoSomething() it simply substitutes the default parameter value and compiles the code as though you had written DoSomething('').

Documentation: Default Parameters.

Overloaded methods

procedure DoSomething(Param: string); overload;
procedure DoSomething; overload;

These methods would be implemented like follows:

procedure TMyClass.DoSomething(Param: string);
begin
  // implement logic of the method here
end;

procedure TMyClass.DoSomething;
begin
  DoSomething('');
end;

Note that the main body of logic is still implemented once only. When writing overloads in this way there will be one master method that performs the work, and a number of other overloads that call that one master method.`

Documentation: Overloading Procedures and Functions.

like image 152
David Heffernan Avatar answered Sep 20 '22 17:09

David Heffernan