Using Nullable Types with Protobuf

Previously, we learned that none of the built-in types in Protobuf are nullable. Each scalar value type, such as string and bool, has a default value. This is the value that a field of this type will be set to if it's not set explicitly.

Not being able to set field values to null comes with a major disadvantage. In some scenarios, we would want to know whether a particular value was set intentionally or no value was provided. The value of null would clearly indicate that no value was provided. However, with the default value, it's impossible to tell. This is why nullable data types can be useful.

In Protobuf, there is a way of making primitive data types nullable. We can do this by importing a built-in package from Google's library of the so-called well-known types. The choice of the name is due to the fact that these types are commonly used by programming languages.

The well-known types library consists of multiple Protobuf files. The framework implicitly references these files. Therefore, none of them need to be added to the project explicitly. All we need to do is add an import statement in the Protobuf file that we want to apply these types in.

Enabling nullable types in Protobuf

We have the following code widget where we have a complete setup of both the gRPC client and server projects. This is where we'll be making all our changes.

Get hands-on with 1400+ tech skills courses.