Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default parameter value for a TSomething in Delphi

I'd like to know if this is possible in Delphi (or if there's a clean way around it):

type
 TSomething = record
  X, Y : Integer;
 end;

GetSomething( x, y ) -> Returns record with those values.

... and then you have this function with TSomething as parameter, and you want to default it as

function Foo( Something : TSomething = GetSomething( 1, 3 );

The compiler spits an error here, however I'm not sure if there's a way around it!

Can this be done?

like image 570
deluvas Avatar asked Sep 20 '10 10:09

deluvas


2 Answers

Use overloading:

procedure Foo(const ASomething: TSomething); overload;
begin
  // do something with ASomething
end;

procedure Foo; overload;
begin
  Foo(GetSomething(1, 3));
end;
like image 57
Uli Gerhardt Avatar answered Sep 23 '22 19:09

Uli Gerhardt


The easiest way is to use overloaded procedures:

program TestOverloading;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TSomething = record
    X,Y : integer;
  end;

const
  cDefaultSomething : TSomething = (X:100; Y:200);

procedure Foo(aSomething : TSomething); overload;
begin
  writeln('X:',aSomething.X);
  writeln('Y:',aSomething.Y);
end;

procedure Foo; overload;
begin
  Foo(cDefaultSomething);
end;

begin
  Foo;
  readln;
end.
like image 41
Svein Bringsli Avatar answered Sep 26 '22 19:09

Svein Bringsli