Are Arrays in Ada Covariant?
Asked Answered
B

1

5

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?

Benoite answered 15/11, 2011 at 23:43 Comment(0)
O
9

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.

Otte answered 16/11, 2011 at 9:41 Comment(4)
Great post. From my understanding this is what I have. No, arrays are not covariant in Ada. The problem is with the memory. When the array is created in Ada it allocates a finite amount of space for each type of a specified object. When you attempt to add a subtype element into the supertype array the computer will not be able give the subtype the amount of space necessary. Java solves this by only holding references to the objects and object references are always the same size.Benoite
"but then you're left with memory management problems" Not if you use the ada.Finalization package and correctly implement your finalize procedure.Aleta
@NWS: true, but OP might feel that came under the heading of "a lot of grief"!Otte
@SimonWright True too... but stating that "Ada doesn't do garbage collection" is wrong so i thought it worth ponting out :)Aleta

© 2022 - 2024 — McMap. All rights reserved.