Default enum field value in protobuf

Enums in protobuf seem pretty obvious. However some of the behaviors are not that simple.

Lets say we have proto:

enum Type {
 ADMIN = 0;
 REGULAR = 1;
}

message User {
 optional Type type = 1;
}

And simple Java code:

User user = User.newBuilder().build();
System.out.println("Has Type: " + user.hasType());
System.out.println("Type: " + user.getType());

Well, field value is optional. So as a Java developer I would expect hasType to return false and getType to return null. However the real output is:

Has Type: false
Type: ADMIN

Why?

public Message.Type getType() {
 Message.Type result = Message.Type.forNumber(type_);
 return result == null ? Message.Type.ADMIN : result;
}

Conclusion: know your libraries and check auto-generated code

This entry was posted in Development, Uncategorized and tagged , . Bookmark the permalink.

Leave a comment