在Person和Address消息定义中使用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编译失败
错误:(98,40)值optionalStreet不是optionalStreet trexo.scalapb.myprotos.Address val emptyAddr = bogusAddr.update(_.optionalStreet := None)的成员
reproduced:在ScalaPB文档中,据说有一种方法可以更新可选字段(为了方便起见,在下面转载)。更新的_.optionalX方式是否更改为不同的语法?
val p = Person().update(
// Pass the value directly:
_.name := "John",
// Use the optionalX prefix and pass an Option:
_.optionalAge := Some(37) // ...or None
)发布于 2020-03-27 09:19:04
在您的实现中,您没有可选字段。如果您希望有一个可选字段,则需要编写如下代码:
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;
}请参见实例中的字段年龄,现在它将是可选的。
https://stackoverflow.com/questions/60876945
复制相似问题