Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Arrays in Ada Covariant?

I know in Java arrays are covariant. So for example:

Assume Dog is a subclass of Animal
In java the arrays are covariant making: Animal[] a supertype of Dog[]
But in java generic collections are not covariant such as: 
ArrayList<Animal> is not a supertype of ArrayList<Dog>

My question is are arrays in Ada Covariant?

like image 363
jbeverid Avatar asked Nov 15 '11 23:11

jbeverid


1 Answers

I think that by "Animal[] [is] a supertype of Dog[]" you mean that Animal[42] might in fact be a Dog? If so, then the answer is No.

In Java, variables (including array elements) are in fact references (think pointers).

Given

type Animal is tagged null record;
type Dog is new Animal with null record;

you can of course say

type Plain_Array is array (Positive range <>) of Animal;

but then all the elements have to be Animals.

To get dispatching in Ada, you have to have a class-wide value to dispatch on, so you could try

type Class_Array is array (Positive range <>) of Animal'Class;

but then the compiler would tell you

gnatmake -c -u -f covariant_arrays.ads
gcc -c covariant_arrays.ads
covariant_arrays.ads:8:59: unconstrained element type in array declaration
gnatmake: "covariant_arrays.ads" compilation error

(Animal and Dog objects aren't the same size). You could try

type Access_Array is array (Positive range <>) of access Animal'Class;

which allows you to say

AA : Access_Array := (1 => new Animal, 2 => new Dog);

but then you're left with memory management problems, because Ada doesn't do garbage collection (at least, with any of the native code compilers I'm aware of). You could save yourself a lot of grief by using Ada.Containers.Indefinite_Vectors.

like image 94
Simon Wright Avatar answered Oct 06 '22 01:10

Simon Wright