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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s