Protobuf (version3) optional field are not nullable in kotlin generated code
Asked Answered
R

0

8

I don't understand why an optional field (like middle_name in the example below), is not nullable in the Kotlin generated representation while in Golang and Rust it is properly nullable (or optional).

syntax = "proto3";

message User{
  string id = 1;
  string name = 2;
  optional string middle_name = 3;
  string last_name = 4;
}

Kotlin generated code

...
public fun hasMiddleName(): kotlin.Boolean{...}
public var middleName: kotlin.String{...}
...

Rust generated code

...
pub middle_name: ::std::option::Option<::std::string::String>,
...

Golang generated code

...
MiddleName *string `protobuf:"bytes,3,opt,name=middle_name,json=middleName,proto3,oneof" json:"middle_name,omitempty"`
...

The only way that I've found is using takeIf method on every attribute access, which is absolutely not error-proof (when forgetting the takeIf check, the code still basically works)

myProto.takeIf{it.hasMiddleName()}?.middleName
Rondelet answered 27/1, 2023 at 13:52 Comment(2)
See github.com/protocolbuffers/protobuf/issues/10178Cascio
@Cascio thank you! You may consider turning your comment into an answer, by summarizing the github thread.Helpful

© 2022 - 2024 — McMap. All rights reserved.