weberc2
weberc2

Reputation: 7908

Ada: Variant records in which a subset of cases share a common property

I have the following code in which I'd like for only the first two cases to share a common property; however, I get the error "id" conflicts with the declaration at line 11 when I try to use this syntax:

   type Shape (Which : Shape_Type := SQUARE) is
      record
      case Which is
         when Square =>
            id : Natural;   -- Line 11
         when Turnout =>
            id : Natural;   -- Line that causes error to be thrown
         when Invalid =>
            null;
      end case;
      end record;

Upvotes: 2

Views: 583

Answers (1)

Simon Wright
Simon Wright

Reputation: 25491

This:

type Shape (Which : Shape_Type := SQUARE) is
   record
      case Which is
         when Square | Turnout =>
            id : Natural;
         when Invalid =>
            null;
      end case;
   end record;

If you later wanted the Turnout case to have an extra attribute, you could do that using a nested case (but you still have to cover all the alternatives):

type Shape (Which : Shape_Type := SQUARE) is
   record
      case Which is
         when Square | Turnout =>
            id : Natural;
            case Which is
               when Square =>
                  null;
               when Turnout =>
                  Deg : Natural;
               when Invalid =>
                  null;
            end case;
         when Invalid =>
            null;
      end case;
   end record;

Upvotes: 5

Related Questions