Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant element in Ada object?

Tags:

ada

In Java or C#, you would often have class members that are final or readonly - they are set once and then never touched again. They can hold different values for different instances of the class.

Is there something similar in Ada? I've tried to create something similar in Ada thusly:

package MyPackage is

   type MyObject is limited new OtherPackage.Object with private;

....

private

   type MyObject (...) is limited new OtherPackage.Object with
      record
         M_MyField : Integer := 10;
         M_MyConstantFactory : constant Factory.Object'Class := new Factory.Object;
      end record;

end MyPackage;

This fails on the declaration of M_MyConstantFactory saying constant components are not permitted. Is there a way around this? A colleague suggested declaring it somewhere else in the package, but that would mean a single M_MyConstantFactory shared across all instances, which is not what I want.

Do I need to just accept that it is possible to modify the value once set and manually guard against that happening?

like image 342
Avi Chapman Avatar asked Sep 10 '18 05:09

Avi Chapman


1 Answers

No. Not quite.

If your component is of a discrete type or an access type, you can make it a discriminant, and thus make it immutable.

with Ada.Integer_Text_IO;

procedure Immutable_Components is

   type Instance (Immutable : Positive) is null record;

   A : Instance := (Immutable => 1);

begin
   Ada.Integer_Text_IO.Put (A.Immutable);

   --  A.Immutable := 2; --  assignment to discriminant not allowed:
end Immutable_Components;
like image 137
Jacob Sparre Andersen Avatar answered Jan 01 '23 18:01

Jacob Sparre Andersen