Ask Your Question
1

How can a Scala case class be created from a Protocol Buffer Compiler generated code from a .proto file?

asked 2022-01-28 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-02-13 14:00:00 +0000

bukephalos gravatar image

To create a Scala case class from a Protocol Buffer Compiler generated code, you could use a library such as "ScalaPB". Here are the steps to follow:

  1. Install the ScalaPB plugin for sbt build tool by adding the following line to your "plugins.sbt" file:
addSbtPlugin("com.thesamet" % "sbt-protoc" % "1.0.1")
  1. Add the ScalaPB dependency to your build.sbt file:
libraryDependencies += "com.thesamet.scalapb" %% "compilerplugin" % "0.10.1"
  1. Create a .proto file that defines your message types:
syntax = "proto3";

package mypackage;

message MyMessage {
  int32 id = 1;
  string name = 2;
}
  1. Compile the .proto file using the sbt-protoc plugin:
sbt compile
  1. The ScalaPB plugin should generate a file called "MyMessage.scala" in your "target/scala-2.12/src_managed/main" directory. This file will contain a case class definition for your message:
package mypackage

case class MyMessage(
  id: Int = 0,
  name: String = ""
)
  1. You can now use the MyMessage case class like any other Scala class:
val message = MyMessage(1, "John")
println(message.id) // prints 1
println(message.name) // prints "John"
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-28 11:00:00 +0000

Seen: 13 times

Last updated: Feb 13 '22