grpc-kotlin icon indicating copy to clipboard operation
grpc-kotlin copied to clipboard

Feature request: better typesafe nullability for message object creation

Open sebek64 opened this issue 2 years ago • 0 comments
trafficstars

Kotlin naturally supports nullability in its type system, which prevents some sort of errors. However, when using protobuf, and especially with proto3, the nullability is not naturally mapped between kotlin world and protobuf world. This can be demonstrated on the following example:

syntax = "proto3";

message MyMessage {
  string name = 1;
}

Here the semantics of name field is basically "required" (the presence is not tracked, but there is a default empty string). The creation of objects of this type then looks like

val obj = myMessage {
    name = "some name"
}

However, nothing prevents me from writing

val obj = myMessage {
}

which simply creates the message with default value in this field. For a field with "required-like" semantics, that leads to more error-prone code.

A better approach would be to generate these methods in a way to treat these fields differently - as explicit parameters of the method:

val obj = myMessage(
  name = "some name",
) {
}

For optional/repeated fields, the old approach can still be used.

On the parsing side, there is also some space for improvement (explicit nullability, immutability, ...), but all that can be solved by transforming the objects after parsing into custom data objects (which is often needed anyway for other reasons). The same can be done for protobuf object creation, but there it is usually just plain overhead, both runtime and dev-time.

I'm open to any feedback and discussion, I can provide more explanation if it is unclear. I'm also willing to provide implementation of this change (but only if the idea is accepted, I don't want to spend time on implementing something that will be rejected anyway).

sebek64 avatar Aug 29 '23 11:08 sebek64