Custom types and collections
ScalaPB lets you customize field types, message types and collection types.
First, make scalapb.proto available
to your project. The examples below show how to supply the Scala types and
TypeMapper instances that the generated code needs.
Primitive wrappers
In proto3, scalar fields declared with optional are wrapped in an Option.
For existing schemas that use wrapper messages, ScalaPB also supports the
standard primitive wrappers in
wrappers.proto.
primitive_wrappers is enabled by default for ScalaPB>=0.6.0. Whenever one
of the standard wrappers is used, it will be mapped to Option[X] where X
is a primitive type. For example:
syntax = "proto3";
import "google/protobuf/wrappers.proto";
message MyMessage {
google.protobuf.Int32Value my_int32 = 5;
}
would generate
case class MyMessage(myInt32: Option[Int]) extends ...
To disable primitive wrappers in a file:
import "scalapb/scalapb.proto";
option (scalapb.options) = {
no_primitive_wrappers: true
};
Custom types
You can customize the Scala type of any field. One use-case for this is when
you would like to use type-safe wrappers around primitive values to enforce unit
correctness. For example, instead of using a raw integer for time fields, you can
wrap them in a Seconds class.
import "scalapb/scalapb.proto";
message Connection {
optional int32 timeout = 1 [(scalapb.field).type = "mydomain.Seconds"];
}
We would like to write code like this:
val c = Connection().update(_.timeout := Seconds(5))
How will ScalaPB know how to convert from the original type (Int) to the
custom type Seconds? For each custom type you need to define an implicit
TypeMapper that will tell ScalaPB how to convert between the custom type and
the base Scala type. A good place to define this implicit is in the companion
object for your custom type, since the Scala compiler will look for a
typemapper there by default. If your typemapper is defined elsewhere, you
will need to import it manually by using the import file-level option.
package mydomain
import scalapb.TypeMapper
case class Seconds(v: Int) extends AnyVal
object Seconds {
implicit val typeMapper: TypeMapper[Int, Seconds] = TypeMapper(Seconds.apply)(_.v)
}
TypeMapper takes two function parameters. The first converts from the original type to
the custom type. The second function converts from the custom type to the
original type.
In addition to primitive values, you can customize enums and messages as well.
For more examples, see:
If you have a TypeMapper that maps a generated type into a type you don't own
(such as String, or a third-party class) then you don't have access to the
companion object to define the typemapper in. Instead, you can place the
typemapper in one of the parent package objects of the generated code. For
example, if you want to map an enum to a string, and the message containing it
goes into the a.b.c package, you can define the type mapper like this:
// src/main/scala/a/b/c/package.scala:
package a.b
package object c {
implicit val segmentType: TypeMapper[SegmentType, String] =
TypeMapper[SegmentType, String](_.name)(SegmentType.fromName(_).get)
}
Lazy String Fields
Since ScalaPB 1.0.0, you can use lazy_utf8_string_fields to decode string fields
only when they are used. This can be useful when your application forwards messages
without reading most of their string fields.
This option is disabled by default. To enable it for a file, add the following option to your proto file. You can override it for individual messages:
syntax = "proto3";
import "scalapb/scalapb.proto";
option (scalapb.options).lazy_utf8_string_fields = true;
message LazyMessage {
string name = 1;
optional string nickname = 2;
repeated string tags = 3;
map<string, string> labels = 4;
}
message NotLazyMessage {
option (scalapb.message).lazy_utf8_string_fields = false;
string name = 1;
}
The message-level option overrides the file-level option, including for that message's map values. String map keys are not lazy.
Regenerate your Scala sources after changing the option. The protobuf wire format stays the same, but the generated Scala API changes. With the default collection and presence settings, the fields above have these types:
| Field | Generated Scala type |
|---|---|
name | LazyField[String] |
nickname | Option[LazyField[String]] |
tags | Seq[LazyField[String]] |
labels | Map[String, LazyField[String]] |
You may need to update code that uses these fields as strings, particularly comparisons and collection operations.
If you specify a custom string type with type or map value_type, that field will
not be lazy. It continues to use your TypeMapper:
message MixedLaziness {
// Lazy when the file enables lazy_utf8_string_fields.
string display_name = 1;
// These fields use the specified custom type and are not lazy.
string person_id = 2 [(scalapb.field).type = "com.thesamet.pb.PersonId"];
map<int32, string> person_ids = 3 [(scalapb.field).value_type = "com.thesamet.pb.PersonId"];
}
Using lazy fields
When parsing a message, ScalaPB reads the string bytes and validates them according
to the configured UTF-8 policy. It converts the bytes to a String the first time
you use the value and caches the result:
val msg = LazyMessage.parseFrom(bytes)
// The bytes have been read and validated according to the configured policy.
// They have not yet been decoded into Strings.
val name = msg.name // Gets the wrapper without decoding.
val text: String = name.value // Decodes once and caches the String.
val upper = name.toUpperCase // An implicit conversion also accesses .value.
val serialized = msg.toByteArray // Writes the stored bytes without re-encoding.
Implicit conversions let you supply strings to generated constructors and pass lazy fields to functions expecting strings:
val created = LazyMessage(name = "Alice", tags = Seq("important"))
def greet(name: String): String = s"Hello, $name"
greet(created.name)
When you assign a String to a lazy field, it is encoded immediately. If you pass a
collection of lazy fields to a function expecting strings, the conversion reads every
value and creates a new collection. You can use .value explicitly to control which
fields are decoded.
The following operations can also decode a field: .value, String methods,
toString (including logging and interpolation), equality between wrappers, and
hashCode. Generated message equality and hashing can therefore decode fields too.
JSON and protobuf text-format output decode the fields they emit; binary
serialization does not.
Equality and collections
A LazyField is equal only to another LazyField with an equal decoded value.
Comparing it directly with a String returns false in either direction. Use
.value to compare the strings:
msg.name.value == "Alice"
msg.nickname.map(_.value).contains("Al")
msg.tags.exists(_.value == "important")
msg.labels.get("team").map(_.value).contains("backend")
You can enable -language:strictEquality in Scala 3 to catch direct comparisons
between a LazyField and a String. In Scala 2, -Xfatal-warnings turns compiler
warnings about these comparisons into errors. These flags do not catch comparisons
through Any.
Typed collections can apply implicit conversions when elements are inserted. An
Any-typed collection keeps wrappers and strings as distinct elements:
import scalapb.LazyField
val name = LazyField.from("Alice")
Set[Any](name, "Alice").size // 2, regardless of insertion order.
Set[String](name, "Alice").size // 1: name is converted to its String value.
UTF-8 validation and Java conversions
Lazy fields follow the same binary parsing policy as regular string fields, including
use_schema_utf8_validation and the schema's UTF-8 settings. By default, malformed
UTF-8 fails the parse with InvalidProtocolBufferException. String map keys and
values always validate during binary parsing.
When validation is disabled for a field, a lazy field preserves the original bytes. Accessing its value replaces malformed UTF-8 with U+FFFD in the decoded String but leaves the stored bytes unchanged. Subsequent binary serialization still writes those original bytes; JSON and text-format output use decoded values. See binary string UTF-8 validation.
Validation is performed by generated binary parsers, not by LazyField.apply. If you
construct a wrapper directly from a ByteString, it is not validated automatically.
Java conversions use byte-string accessors for singular and repeated string fields.
When converting to Java, set<Name>Bytes/add<Name>Bytes follow the target Java
schema's UTF-8 validation policy and can reject malformed input when validation is
enabled. Full Java protobuf can preserve malformed bytes when validation is disabled.
See UTF-8 validation in
Java.
Java map values have String-based accessors, so their conversion requires UTF-8 decoding/encoding. Converting a manually constructed lazy map value containing malformed bytes to Java replaces those bytes with replacement characters.
When to use lazy strings
Lazy strings are most useful when forwarding or modifying messages while reading only a small fraction of their string fields. Avoiding UTF-8 decoding and re-encoding can be particularly useful for non-ASCII text.
The benefit depends on how many string fields your application reads. Each lazy field adds a wrapper allocation, and after decoding it retains both its bytes and its String. Reading most fields, logging whole messages, or using messages as hash keys can reduce the benefit and increase memory use. You can use the benchmarks to measure the effect on your workload.
Message-level custom type and boxing
In the previous section you saw how to customize the type generated for a
specific field. ScalaPB also lets you specify a custom type at the message
level. When type is set at the message level, that type is used for all the
fields that use that message. This eliminates the need to specify type on each field
of this type.
// duration.proto
syntax = "proto3";
package mytypes;
import "scalapb/scalapb.proto";
message Duration {
option (scalapb.message).type = "mytypes.MyDurationClass";
int32 seconds = 1;
}
In a Scala file define an implicit mapper:
import scalapb.TypeMapper
import mytypes.duration.Duration
case class MyDurationClass(seconds: Int)
object MyDurationClass {
implicit val tm: TypeMapper[Duration, MyDurationClass] = TypeMapper[Duration, MyDurationClass] {
d: Duration => MyDurationClass(d.seconds) } {
m: MyDurationClass => Duration(m.seconds)
}
}
Now, each time you reference Duration in a proto file, the generated field in Scala code
will use the custom type MyDurationClass:
syntax = "proto3";
package mytypes;
import "scalapb/scalapb.proto";
import "duration.proto";
message Usage {
Duration dd = 1; // will become dd: Option[MyDurationClass]
repeated Duration ds = 2; // will become ds: Seq[MyDurationClass]
// You can eliminate the boxing of an optional field in an Option by using
// no_box
Duration dd_nobox = 3 [(scalapb.field).no_box = true]; // will become ddNoBox: MyDurationClass
}
If you do not want any instance of your message to be boxed (regardless if it
has a custom type), you can set no_box at the message-level:
// duration_nobox.proto
syntax = "proto3";
package mytypes;
import "scalapb/scalapb.proto";
message Duration {
option (scalapb.message).type = "mytypes.MyDurationType";
option (scalapb.message).no_box = true; // do not wrap in Option
int32 seconds = 1;
}
Then when this message is used, it will not be wrapped in an Option. If
no_box is specified at the field level, it overrides the value specified at
the message level.
Custom types on maps
Since version 0.6.0 it is possible to customize the key and value types of
maps. Like the custom types described above you will need to have a TypeMapper
for the custom type.
Example:
message CustomMaps {
// Will generate Map[String, com.thesamet.pb.Years]
map<string, int32> string_to_year = 1 [
(scalapb.field).value_type = "com.thesamet.pb.Years"];
// Will generate Map[PersonId, Int]
map<string, int32> person_to_int = 2 [
(scalapb.field).key_type = "com.thesamet.pb.PersonId"];
// Will generate Map[PersonId, com.thesamet.pb.Years]
map<string, int32> person_to_year = 3 [
(scalapb.field).key_type = "com.thesamet.pb.PersonId",
(scalapb.field).value_type = "com.thesamet.pb.Years"];
}
Example: see CustomMaps in maps.proto
You can also customize the collection type used for a map. See the next section for details.
Custom collection types
By default, ScalaPB compiles repeated fields into a Seq[T]. When a message
is parsed from bytes, the default implementation instantiates a Vector[T],
which is a subtype of Seq[T]. You can instruct ScalaPB to use a different
collection type for one field by specifying the collection_type option. You
can also specify a collection_type for the entire proto file by specifying a
collection_type at the file-level.
If both are defined then the field-level setting wins.
Similar to collection_type, we have map_type for map types. By default,
ScalaPB generates scala.collection.immutable.Map for maps, and you can
customize it at the field level, or file-level by specifying a map_type
option.
map_type was introduced in ScalaPB 0.8.5.
import "scalapb/scalapb.proto";
option (scalapb.options) = {
collection_type: "Set"
};
message CollTest {
// Will generate Set[Int] due to file-level option.
repeated int32 rep1 = 1;
// Will generate an Array[String]
repeated string rep2 = 2 [
(scalapb.field).collection_type="Array"];
// Will generate collection.immutable.Seq[Boolean]
repeated bool rep3 = 3 [
(scalapb.field).collection_type="collection.immutable.Seq"];
map<int32, string> my_map = 4 [
(scalapb.field).map_type="collection.mutable.Map"];
}
Note on mutable collection: ScalaPB assumes that all data is immutable. For example, the result
of serializedSize is cached in a private field. When choosing mutable collections, you must be
careful not to mutate any collection after it has been passed to any message, or you might get some
surprising results!
Note: using Array is not supported along with Java conversions.
Note: Most Scala collections can be used with this feature. If you are trying
to implement your own collection type, it may be useful to check MyVector
and MyMap, the simplest custom collection that is compatible with ScalaPB: