ScalaPB,proto3:将字段设置为 None,没有可用的可选 X 前缀

ScalaPB, proto3: set field to None, no optionalX prefix available

使用 PersonAddress 中的消息定义 https://scalapb.github.io/generated-code.html

syntax = "proto3";
package trexo.scalapb;

message Person {
  string name = 1;
  int32 age = 2;

  repeated Address addresses = 3;
}

message Address {
  string street = 1;
  string city = 2;
}

构建设置为:

// project/plugins.sbt
addSbtPlugin("com.thesamet" % "sbt-protoc" % "0.99.28")
libraryDependencies += "com.thesamet.scalapb" %% "compilerplugin" % "0.10.1"

// build.sbt
name         := "ProtobufPlayAround"
version      := "0.1"
scalaVersion := "2.12.10"

PB.targets in Compile := Seq(
  scalapb.gen() -> (sourceManaged in Compile).value
)

val scalapbVersion = scalapb.compiler.Version.scalapbVersion

libraryDependencies ++= Seq(
  "org.scalatest" %% "scalatest" % "3.1.1" % "test",
  "com.thesamet.scalapb" %% "scalapb-runtime" % scalapbVersion  % "protobuf"
)

然后我创建了一个测试:

import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import trexo.scalapb.myprotos.{Address, Person}

class SerializeSpec extends AnyFreeSpec with Matchers {
  "TEST #1 .update() with concrete value (no Option)" in {
    val street1 = "Mount Everest"
    val city1   = "Himālaya"

    val expectedAddr = Address(street1, city1)

    val updAddr = Address().update(
      _.street := street1,
      _.city   := city1
    )
    updAddr shouldEqual expectedAddr
  }

  "TEST #2 .update() with Option value" in {
    val bogusAddr = Address(street = "Huh?", city = "Ah?")

    val emptyAddr = bogusAddr.update(
      _.optionalStreet := None,
      _.optionalCity   := None
    )

    emptyAddr shouldEqual Address()
  }
}

测试 #1 通过。测试 #2 编译失败

Error:(98, 40) value optionalStreet is not a member of scalapb.lenses.Lens[trexo.scalapb.myprotos.Address,trexo.scalapb.myprotos.Address] val emptyAddr = bogusAddr.update(_.optionalStreet := None)

问题: 在ScalaPB 文档中,Optional Fields 据说有一种方法可以更新可选字段(为方便起见转载如下)。 _.optionalX 更新方式是否更改为不同的语法?

val p = Person().update(
  // Pass the value directly:
  _.name := "John",

  // Use the optionalX prefix and pass an Option:
  _.optionalAge := Some(37)  // ...or None
)

在您的实施中,您没有可选字段。如果你想有一个可选字段,你需要编写这样的代码:

syntax = "proto3";
package trexo.scalapb;
import "google/protobuf/wrappers.proto";

message Person {
  string name = 1;
  google.protobuf.Int32Value age = 2;

  repeated Address addresses = 3;
}

message Address {
  string street = 1;
  string city = 2;
}

请参阅示例字段年龄,现在它将是可选的。