在新消息中使用任何以前的消息

Use any previous message in a new message

我有一个 protobuf 文件,我在其中定义了多条消息,它们都继承了相同的特征(在消息定义中使用 option (scalapb.message).extends = "Event";)。

我想创建一个名为 MultiEvent 的新消息,它可能包含从 Event 继承的任何消息的序列。

事件在 scala 代码中被定义为简单的 trait Event

想法是能够一次发送包含多条消息的特殊消息。

syntax = "proto3";

import "scalapb/scalapb.proto";

package com.some.package;

message A {
  option (scalapb.message).extends = "Event";
  string name = 1;
}

message B {
  option (scalapb.message).extends = "Event";
  string field = 1;
}

message C {
  option (scalapb.message).extends = "Event";
  string otherField = 1;
}

message MultiEvent {
  option (scalapb.message).extends = "Event";
  repeated Event seq = 1; // this line is problematic
}

我收到错误:"Event" is not defined.。 理想情况下,从代码来看,该字段将是一个简单的 Seq,它重复提供,但它仅适用于标量类型。 我在网上发现Any也许可以完成我想要的,但是我尝试使用它时出现错误。

通常解决此类问题的方法是什么?枚举?转换?

谢谢。

通常的方式是oneof(在 Protocol Buffers 3 中)。 repeated oneof 不合法:

Repeated oneof was in the initial proposal but as we later found out, there were lots many complicated corner cases in wire and API. We decided not to add repeated for oneof.

You can always define a message which wraps a oneof and have a repeated field of that message instead.

所以

message Event {
  oneof sealed_value {
    A a = 1;
    B b = 2;
    C c = 3;
    ...
  }
}

然后是 repeated Event,就像你目前拥有的那样。

使用 sealed_value 作为名称启用 ScalaPB 的 sealed oneof 支持。