使用scalapb为地图编写TypeMapper

时间:2019-05-14 17:27:58

标签: scala scalapb

在包装由map的protobuf生成的案例类中,我想制作Option

case class Foo(aMap: Option[Map[String, String]])

为此,我尝试使用scalapb.TypeMapper

package some.wrapper
import scalapb.TypeMapper
case class StringMapWrapper(map: Map[String, String])
object StringMapWrapper {
  implicit val mapper = TypeMapper(StringMapWrapper.apply)(_.map)
}

原始文件如下:

syntax = "proto3";
package some;
import "scalapb/scalapb.proto";
message Foo {
  map<string, string> a_map = 1 [(scalapb.field).type = "some.wrapper.StringMapWrapper"];
}

但是在编译过程中出现错误: --scala_out: some.Foo.a_map: Field a_map is a map and has type specified. Use key_type or value_type instead.

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

ScalaPB中在Option内获取内容的标准方法是将其包装在消息中:

syntax = "proto3";
package some;
import "scalapb/scalapb.proto";

message OptionalMap {
  option (scalapb.message).type = "Map[String, String]";
  map<string, string> inner = 1;
}

message UseCase {
  OptionalMap my_map = 1;
}

由于type上的OptionalMap选项,ScalaPB会将myMap生成为Option[Map[String, String]]而不是Option[OptionalMap]。然后,我们唯一需要知道的是提供一个TypeMapper,它将教ScalaPB在OptionalMap和Map [String,String]之间进行转换。为此,请将以下内容添加到包对象UseCase中:

package object some {
  implicit val OptionalMapMapper =
      scalapb.TypeMapper[some.myfile.OptionalMap, Map[String, String]](_.inner)(some.myfile.OptionalMap(_))
}