Search code examples
recordada

Why is named association required for a one-element record aggregate?


When an aggregate contains only one element, as below, positional notation results in a compilation error and we have to use named notation only. Why?

type singleton is record
   v : integer;
end record;

v1 : singleton := (0);

results in the compiler message

check.adb:6:23: positional aggregate cannot have one component
check.adb:6:23: write instead "V => ..."
gnatmake: “check.adb" compilation error

whereas this is OK:

v2 : singleton := (v => 0);

Solution

  • Parentheses round an expression are redundant, so (0) = 0 and it's an integer not an array aggregate.

    So, for the special case of a one-element aggregate, named association is required to distinguish an aggregate from a simple value.

    Contrast this with (0,0) which can only be an aggregate; therefore there is no ambiguity.

    Even though in the context of the question, it's obvious to a human programmer which is intended, that will not always be the case.

    Consider a one-element aggregate in a multi-dimensional array which is one field of a record; there can be ambiguities that the compiler cannot resolve (at least, before reading a whole lot more of the source file!) and would make life pretty difficult for anyone reading the program.