Methods in Ada

Ada supports methods defined on record types, which are similar to structs in other languages.

with Ada.Text_IO; use Ada.Text_IO;

procedure Methods is
   type Rect is record
      Width, Height : Integer;
   end record;

   -- This Area function has a parameter of type Rect
   function Area (R : Rect) return Integer is
   begin
      return R.Width * R.Height;
   end Area;

   -- Here's another function with a parameter of type Rect
   function Perim (R : Rect) return Integer is
   begin
      return 2 * R.Width + 2 * R.Height;
   end Perim;

   R : Rect := (Width => 10, Height => 5);
begin
   -- Here we call the 2 functions defined for our record
   Put_Line ("area: " & Integer'Image (Area (R)));
   Put_Line ("perim:" & Integer'Image (Perim (R)));

   -- Ada doesn't have pointers in the same way as some other languages,
   -- but we can use access types if we need reference semantics
   declare
      type Rect_Access is access all Rect;
      RP : Rect_Access := new Rect'(R);
   begin
      Put_Line ("area: " & Integer'Image (Area (RP.all)));
      Put_Line ("perim:" & Integer'Image (Perim (RP.all)));
   end;
end Methods;

In Ada, we don’t have methods in the same way as in some object-oriented languages. Instead, we define functions that take the record as a parameter. This achieves a similar result to methods in other languages.

Ada doesn’t have the concept of receiver types in the same way. Instead, we pass the record as a parameter to our functions. The Area and Perim functions both take a Rect as their parameter.

Ada uses strong typing, so we don’t need to worry about automatic conversion between values and pointers. If we want to work with a reference to a record, we can use an access type (Ada’s version of pointers).

To run this program:

$ gnatmake methods.adb
$ ./methods
area:  50
perim: 30
area:  50
perim: 30

Next, we’ll look at Ada’s mechanism for grouping and naming related sets of operations: packages.