Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java Protocol Buffers ever return null on the list getter of a repeated field?

Say you have a repeated field.

message Foo {
  optional int32 val = 1;
}

message Bar {
  repeated Foo foo = 1;
}

This will generate the method

List<Foo> getFooList()

Is there any circumstance where getFooList will return null? Or will it already return a List, even if it's empty?

like image 237
Kat Avatar asked Jan 02 '14 20:01

Kat


People also ask

Can protobuf have NULL values?

Turns out, protobuf does not allow setting null values on any object field. The setters generated from proto files come with null pointer exceptions right out of the box.

Are repeated fields ordered in protobuf?

Yes, repeated fields retain the order of items. From Google's Protocol Buffers encoding specification: The order of the elements with respect to each other is preserved when parsing, though the ordering with respect to other fields is lost.

What is repeated field in protobuf?

repeated : this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.

How do I set default value in protobuf?

For bool s, the default value is false. For numeric types, the default value is zero. For enums , the default value is the first value listed in the enum's type definition. This means care must be taken when adding a value to the beginning of an enum value list.


3 Answers

No, there is no case where it returns null. In fact, none of the field accessors on Java protobuf generated classes ever return null; they always return the default value if the field is not present. Similarly, the setters do not allow you to set null.

like image 165
Kenton Varda Avatar answered Oct 08 '22 19:10

Kenton Varda


Note that no Java protocol buffer methods accept or return nulls unless otherwise specified.

Reference: https://developers.google.com/protocol-buffers/docs/reference/java-generated

like image 31
Tyrael Avatar answered Oct 08 '22 20:10

Tyrael


The default value for repeated fields is empty (generally an empty list in the appropriate language).

Source: https://developers.google.com/protocol-buffers/docs/proto3#default

like image 1
Lu55 Avatar answered Oct 08 '22 19:10

Lu55