Reputation: 93
I am creating a converter method between two protobuf messages A and B:
message A {
optional int64 id = 1;
optional string name = 2;
}
message B {
optional int64 id = 1;
optional C c= 2;
}
message C {
optional string name = 1;
}
My code is the following:
private A convertFromBToA(B b) {
return A.newBuilder()
.setId(B.getId())
.setName(b.hasC() ? b.getC().getName() : null).build();
}
Essentially, I only want to set the name field of message A if B's C field has a name field. Otherwise I want to leave A's name field unset. Is this the correct way to do so?
Upvotes: 1
Views: 1051
Reputation: 239521
Just use an if
to conditionally call setName
only if you have a name to set, rather than always calling setName
even when there is no argument to give it:
A a = A.newBuilder().setId(B.getId())
if (b.hasC()) {
a = a.setName(b.getC());
}
return a.build();
Upvotes: 2