Writing generic code
In some cases you will want to write generic code that can handle arbitrary message types. This guide will show you various techniques that you can use to accomplish that.
Generated types#
For each message in your proto files, ScalaPB will generate a case class which
extends the GeneratedMessage[MessageType] and a companion object:
Generally speaking, the case class would have methods that act on a given instance. Here are the important ones:
The companion, in turn, provides methods to create new instances of the type,
as well as retrieving the descriptors of the messages. The descriptors can be
used to query structural information about the proto files at runtime. Note
that the GeneratedMessageCompanion takes a type parameter A which
represents the message case class (must be a subtype of GeneratedMessage):
Writing a function that accepts any message type#
The following is an example of a function that takes an instance of a message and writes it to a file.
Summoning the companion#
In our next example, we will write a function that reads a file and parse it
into a message of type A. To build a new instance of a message, we need to
call parseFrom on the companion. Using Scala's implicit search, it is easy
to obtain the companion of any message type:
When calling this function, you need to provide the specific type you want it
to return, and the filename. The Scala compiler will automatically find the
appropriate message companion to pass as cmp via implicit search: