Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: better typesafe nullability for message object creation #415

Open
sebek64 opened this issue Aug 29, 2023 · 0 comments
Open
Assignees

Comments

@sebek64
Copy link

sebek64 commented Aug 29, 2023

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants