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?

   <b>package</b> P <b>is</b>
      <b>type</b> T <b>is</b> <b>private</b>;
      …
   <b>private</b>
      <b>type</b> T <b>is</b>
         <b>record</b>
            Color : Color_Enum := Red;
            Is_Gnarly : Boolean := False;
            Count : Natural;
         <b>end</b> <b>record</b>;
   <b>end</b> P;
   <b>package</b> <b>body</b> P <b>is</b>
      Object_100 : <b>constant</b> T := 
         (Color => Red, Is_Gnarly => False, Count => 100);
      …
   <b>end</b> 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 : <b>constant</b> 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 : <b>constant</b> T := (Count => 100, <b>others</b> => <>);

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”.


Last Updated: 10/26/2017
Posted on: 10/8/2007