Alperen
Alperen

Reputation: 4612

Different enums, same value in protobuf

I have protocol buffer definitions like this:

package com.asd;

enum AType {
    A1 = 0;
    A2 = 1;
    Unknown = 2;
}

enum BType {
    B1 = 0;
    B2 = 1;
    Unknown = 2;
}

While compiling, I am getting this error:

"Unknown" is already defined in "com.asd". Note that enum values use C++ scoping rules, meaning that enum values are siblings of their type, not children of it. Therefore, "Other" must be unique within "com.asd", not just within "BType".

Is there a workaround for this problem other than using different packages?

Upvotes: 16

Views: 15564

Answers (2)

Alperen
Alperen

Reputation: 4612

I believe there is no straightforward way of using the same enum value in the same package but there are two workarounds (link):

  1. Use prefix:

     package com.asd;
    
     enum AType {
         AType_A1 = 0;
         AType_A2 = 1;
         AType_Unknown = 2;
     }
    
     enum BType {
         BType_B1 = 0;
         BType_B2 = 1;
         BType_Unknown = 2;
     }
    
  2. Put the enums in different messages:

     message ATypeMessage{
         enum AType{
             A1 = 0;
             A2 = 1;
             Unknown = 2;
         }
     }
    
     message BTypeMessage{
         enum BType{
             B1 = 0;
             B2 = 1;
             Unknown = 2;   
         }
     }
    

Upvotes: 19

Sirode
Sirode

Reputation: 597

I don't have enough reputation to post this as a comment, and my suggestion is a hack that might not even work. But have you tried to add the option allow_alias = true; in both enum and use the same value.

Ref: https://developers.google.com/protocol-buffers/docs/proto#enum

Upvotes: 1

Related Questions