Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Overloading and Default Parameters, any other option in Delphi ?

Tags:

delphi

I get a set numbers like A, B, C, D in my program , sometimes I need to calc the sum of several of theses numbers like :

    function DoIt2 (a, b : Integer) : Integer ; overload
    begin
        result := a +b ; 
    end;


    function DoIt3 (a, b, c : Integer) : Integer ; overload
    begin
        result := a +b +c  ; 
    end;

there are many DoIt's function involved in my problem. I can not use e.g. a IntegerList as I need to Know what has been A and B and so on ..... Any good solution compared to endless function overloading ?

like image 234
Franz Avatar asked Jan 18 '26 15:01

Franz


1 Answers

You should use an open array:

function Sum(const Values: array of Integer): Integer;
var
  i: Integer;
begin
  Result := 0;
  for i := low(Values) to high(Values) do
    Result := Result + Values[i];
  end;
end;

And call it like this, using an open array constructor:

x := Sum([1, 2]);
y := Sum([1, 2, 3]);
z := Sum([42, 666, 29, 1, 2, 3]);
i := Sum([x, y, z]);

and so on.

In fact, you'll find this very function (names SumInt for the integer version), and many similar, already implemented in the Math unit.

like image 130
David Heffernan Avatar answered Jan 20 '26 14:01

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!