Gem #12: Limited Types in Ada 2005 — <> Notation Part 2

by Bob Duff —AdaCore

Let's get started…

Have you ever written Ada 95 code like this?

   package P is
      type T is private;
      …
   private
      type T is
         record
            Color : Color_Enum := Red;
            Is_Gnarly : Boolean := False;
            Count : Natural;
         end record;
   end P;
   package body P is
      Object_100 : constant T := 
         (Color => Red, Is_Gnarly => False, Count => 100);
      …
   end P;

We want Object_100 to be a default-initialized T, with Count equal to 100. It's a little bit annoying that we had to write the default values Red and False twice. What if we change our mind about Red, and forget to change it in all the relevant places?

The “<>” notation comes to the rescue. If we want to say, “make Count equal 100, but initialize Color and Is_Gnarly to their defaults”, we can do this:

   Object_100 : constant T := 
      (Color => <>, Is_Gnarly => <>, Count => 100);

On the other hand, if we want to say, “make Count equal 100, but initialize all other components, including the ones we might add next week, to their defaults”, we can do this:

   Object_100 : constant T := (Count => 100, others => <>);

Note that if we add a component “Glorp : Integer;” to type T, then the “others” case leaves Glorp undefined just as this Ada 95 code would do:

   Object_100 : T;
   Object_100.Count := 100;

Think twice before using “others”.