C.2. Function Overload - JulTob/Ada GitHub Wiki

Primitive functions Overload

Primitive functions can be overwritten for a new type instead of just heritage from father types.

use type NewType; --Brings primitives to scope.

function "=" (Left : NewType, Right : NewType) return Boolean;

function "+"(Left,Right : NewType) return NewType;

function "-"(Left,Right : NewType) return NewType;

function "*"(Left,Right : NewType) return NewType;

function "/"(Left,Right : NewType) return NewType;
Divide_By_Zero : Exception;
function "/"(Left,Right : NewType) return NewType is
begin
   if Right = 0 then
      raise Divide_By_Zero;
   end if;
   ...
end "/";

when NPackage.Divide_By_Zero => 
    Put_Line("Division By Zero");

Function Overload

Self made Operations with other types.


with Ada.Text_IO;

procedure hello_function_overload is

  function Func
      (N: in Integer) 
    return Integer;
  function Func
      (N: in Integer; 
       M: in Integer) 
    return Integer;


  function Func(N: in Integer) return Integer 
  begin
    return N+1;
  end Func;
  
    function Func(N: in Integer; M: in Integer) return Integer 
  begin
    return N+M;
  end Func;

  package T_IO renames Ada.Text_IO;

  N:Integer:=2;
  M:Integer:=3;
  
begin --hello_function_overload
  T_IO.Put_Line(Integer'Image(N));
  N:=Func(N);
  T_IO.Put_Line(Integer'Image(N));
  T_IO.Put_Line(Integer'Image(M));
  T_IO.Put_Line(Integer'Image( Func(N,M) ));


  
end hello_function_overload;

-- Triple
-- Demonstrates function overloading

WITH Text_Io;                  USE Text_Io;
WITH Ada.Integer_Text_IO;      USE Ada.Integer_Text_IO;

PROCEDURE TripleV2 IS

   FUNCTION Triple (Inp : Integer) RETURN Integer IS
   BEGIN
      RETURN Inp * 3;
   END;

   FUNCTION Triple (Inp : Integer) RETURN String IS
      InpS : string := Integer'image(Inp);
   BEGIN
      RETURN InpS & InpS & InpS;
   END;

BEGIN
   Put( "Tripling 5: "); Ada.integer_text_io.Put(Triple(5), 1); New_Line(2);
   Put( "Tripling 'gamer': "); text_io.Put(Triple(5)); New_Line;
END;