Protobuf: Can not define two same enum name in the same proto file

Created on 5 Dec 2018  路  5Comments  路  Source: protocolbuffers/protobuf

Version: grpc-protobuf 1.14.0
Language: Java
OS: Windows 7

Steps to reproduce the behavior:
Define the following two enum in the same proto file, both TestEnum1 and TestEnum2 have a enum constant named UNKNOWN.

enum TestEnum1 {
    IDLE = 0;
    RUNNING = 1;
    UNKNOWN = -1;
}

enum TestEnum2 {
    MAN = 0;
    ANIMAL = 1;
    UNKNOWN = -1;
}

What did you expect to see
The proto will be compiled successfully.

What did you see instead?
I got the following compile error:
"UNKNOWN" is already defined in "xxx".

And it's interesting that we can't define two same enum constant in the same proto file, but protobuf will add a UNRECOGNIZED enum constant to every enum in the Java class generated after compiling.

Most helpful comment

@acozzette
Although this behavior is expected, it's really not friendly to developer. Values in different enums don't conflict with each other in Java.

All 5 comments

This behavior is actually expected. The enum values go into the scope enclosing the whole enum definition, so in cases like your example, values in different enums can still conflict with each other. Probably the best way around it is just to put a prefix in front of UNKNOWN, like TEST_ENUM1_UNKNOWN for example.

@acozzette
Although this behavior is expected, it's really not friendly to developer. Values in different enums don't conflict with each other in Java.

The general proto syntax has to taken all supported languages into account.

Isn't it possible to use scoped enums for c++ 11 and implement an option to specify which enums to be used. We mainly use Java and it's seriously utterly stupid that this requires these kinds of hacks.

Same applies in Go where the enum value gets prefixed with the enum name automatically by the code generator.
Manually adding the enum name again as a prefix in the enum value results in stuttering and is very unpleasant to read and use 馃槩

Was this page helpful?
0 / 5 - 0 ratings

Related issues

twmht picture twmht  路  3Comments

TimmKayserHere picture TimmKayserHere  路  3Comments

Nayan-Das picture Nayan-Das  路  3Comments

dwsutherland picture dwsutherland  路  3Comments

nvarini picture nvarini  路  3Comments