Add option to make message type fields always nullable
Opened this issue · 5 comments
In proto3, message type fields are always optional; adding the optional keyword does not change the compiled java code
i.e)
message Message {
Field field = 1;
}
message Field {
string name = 1;
}
is equal to
message Message {
optional Field field = 1;
}
message Field {
string name = 1;
}
However, krotoDC currently generates different code for these two cases
data class Message(
val field: Field = Field()
)
data class Message(
val field: Field? = null
)
Because of this, when a krotoDC message type field is not set, while message type fields with the optional keyword are "unset", fields without the keyword is set with an empty message (with all fields unset).
Strictly speaking, this contradicts the proto3 syntax's basic rule; that all message fields are optional. But it is true that this difference could be preferred for certain cases.
The best way to go would be adding an option for the krotoDC protoc plugin that when enabled, creates all message type fields as nullable. then, if this is preferred by the majority of users, we could adpot it as the default behavior
I prefer the current implementation. We have a convention of adding optional
to every field explicitly. But generally, It makes more sense to generate all of them nullable
by default, because this convention is just a thing we made up.
Also, if field
is unset in the non-null implementation, are we seeing a NullPointerException
in runtime?
We use https://github.com/bufbuild/protovalidate
to ensure field nullability for example. I had a long conversation in pbandk issues. Ability to generate code as nullable or not nullable based on certain options. What do you think about this?
Also, if field is unset in the non-null implementation, are we seeing a NullPointerException in runtime?
No, these fields are set with default instances
I also agree that having an option for both is the best way to go.
Also, if field is unset in the non-null implementation, are we seeing a NullPointerException in runtime?
No, these fields are set with default instances
One reason why Proto uses unset
as the default instance rather than null
is recursion
message LinkedList {
string value = 1;
LinkedList next = 2;
}
In this case, the generated code shouldn't really work, right? I assume Kotlin code looks like this:
data class LinkedList(
val value: String,
val next: LinkedList,
)
Which is basically impossible to initialize. As long as code throws an appropriate error, I like it.