views:

173

answers:

4

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?

+3  A: 

Use a class instead of a record and something like this would do it:

TSomething = class
public 
  X: integer;
  Y: integer
end;

procedure Foo(Something: TSomething = nil);
begin
  if (Something = nil) then
    Something := GetSomething(1, 3);
  ...
end;
splash
To exclude some RTTI overhead, X and Y could be declared as 'public' instead of implicit 'published'
mjustin
Thank you @mjustin for pointing this out. My implicit assumption was, that the directive to control the generation of RTTI is set to the default value: `{$M-}`. ;-)
splash
+9  A: 

Use overloading:

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

procedure Foo; overload;
begin
  Foo(GetSomething(1, 3));
end;
Ulrich Gerhardt
+2  A: 

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.
Svein Bringsli
-1 for duplicating Ulrich's answer.
splash
@Splash: Sorry, didn't see it. I spent a long time entering my answer, since I started right before lunch and finished after lunch :-) Should've doublechecked before posting.
Svein Bringsli
@Svein, I hope you aren't *overloaded* after the lunch!? ;-)
splash
A: 

It is not possible to use a function as a default value. The answers with overload examples is the right way to go.

Eduardo Mauro