Skip to main content

Customizations

Getting started with scalapb.proto​

ScalaPB's code generator supports many different customizations. To get access to these customizations, you need to import scalapb/scalapb.proto in the proto files you want to customize. You can also have the options apply to an entire protobuf package by using package-scoped options (see below).

To have scalapb/scalapb.proto available to be imported in your project, add the following SBT setting in your build.sbt:

libraryDependencies += "com.thesamet.scalapb" %% "scalapb-runtime" % scalapb.compiler.Version.scalapbVersion % "protobuf"

If you are invoking protoc manually, you will need to ensure that the files in protobuf directory are available to your project.

Choosing a customization​

Use the options below to customize generated declarations. For other tasks, see:

ScalaPB File-level Options​

ScalaPB file-level options let you

  • specify the name of the Scala package to use (the default is using the java package name).
  • request that ScalaPB will not append the protofile name to the package name.
  • specify Scala imports so custom base traits and custom types (see below) do not require the full class name.

The file-level options are not required, unless you are interested in those customizations. If you do not want to customize the defaults, you can safely skip this section.

File-level options​

import "scalapb/scalapb.proto";

option (scalapb.options) = {
scope: FILE
package_name: "com.example.myprotos"
flat_package: true
single_file: true
java_conversions: false
import: "com.thesamet.pb.MyType"
import: "com.thesamet.other._"
preamble: "sealed trait BaseMessage"
preamble: "sealed trait CommonMessage"
lenses: true
getters: true
retain_source_code_info: false
no_default_values_in_constructor: false
preserve_unknown_fields: true
enum_value_naming: CAMEL_CASE
enum_strip_prefix: false
bytes_type: "scodec.bits.ByteVector"
scala3_sources: false
public_constructor_parameters: false
};
  • scope controls whether the specified options apply only for this proto file or for the entire package. Default is FILE. See package-scoped options for more details.

  • package_name sets the Scala base package name, if this is not defined, then it falls back to the java_package option. If the java_package option is also not found, then the package name from file's package statement is used.

  • Setting flat_package to true (default is false) makes ScalaPB not append the protofile base name to the package name. You can also apply this option globally to all files by adding it to your ScalaPB SBT Settings.

  • The single_file option makes the generator output all messages and enums to a single Scala file.

  • The java_conversions option tells ScalaPB to generate converters to the corresponding Java messages in this file. It does not automatically trigger Java source code generation for the messages. If you need to generate source code in Java, include PB.gens.java in the list of targets in sbt-protoc. Conversions preserve unknown fields when unknown-field preservation is enabled. Declared fields and unknown fields are copied directly. For extendable messages, only Java-registered extensions are serialized to preserve their wire data. toJavaProto retains extension data as unknown fields; for typed Java extension access, reparse the result's bytes with an ExtensionRegistry. The conversion methods do not take a registry. Regenerate sources with the updated generator and use the matching runtime to enable unknown-field preservation.

  • The preamble is a list of strings that is output at the top of the generated Scala file. This option requires single_file to be set. It is commonly used to define sealed traits that are extended using (scalapb.message).extends - see custom base traits below and this example.

  • The object_name option lets you customize the name of the generated class that contains various file-level members such as descriptors and a list of companion objects for the generated messages and enums. This is useful in case you are running into issues where the generated class name conflicts with other things in your project.

  • Setting lenses to false inhibits generation of lenses (default is true).

  • Setting getters to false inhibits generation of getters (default is true).

  • Setting retain_source_code_info to true retains information in the descriptor that can be used to retrieve source code information from the descriptor at runtime (such as comments and source code locations). This option is turned off by default to conserve source size and memory at runtime. When this option is enabled, use the location method on various descriptors to access source code information.

  • By default, all non-required fields have default values in the constructor of the generated case classes. When setting no_default_values_in_constructor to true no default values will be generated for all fields. There is also a message-level no_default_values_in_constructor and field-level no_default_value_in_constructor. If the field-level setting is set, it overrides the message-level. If the message-level setting is set, it overrides the file-level setting.

  • Typically, enum values appear in UPPER_CASE in proto files, and ScalaPB generates case objects with exactly the same name in Scala. If you would like ScalaPB to transform the names into CamelCase, set enum_value_naming to CAMEL_CASE.

  • It is a common practice in protobufs to prefix each enum value name with the name of the enum. For example, an enum name Size may have values named SIZE_SMALL and SIZE_LARGE. When you set enum_strip_prefix to true, ScalaPB will strip the enum's name from each value name, and they would become SMALL and LARGE. Then the name can be transformed to camel-case according to enum_value_naming. Note that the prefix that is removed is the all-caps version of the enum name followed by an underscore.

  • By default, generated messages preserve unknown fields during deserialization. Set preserve_unknown_fields to false to discard them. The default has been true since ScalaPB 0.10.0, for consistency with Java.

  • Use bytes_type to customize the Scala type used for the bytes field type. You will need to have an implicit TypeMapper[com.google.protobuf.ByteString, YourType] instance so ScalaPb can convert back and forth to the type of your choice. That implicit will be found if it is defined under YourType companion object, or on a package object that matches the generated code (or any of its parent packages).

  • By default, ScalaPB generates Scala sources that are compatible with both Scala 2 and Scala 3. To generate Scala 3-only sources using given definitions, compatible with -source:future, set scala3_sources to true or pass the scala3_sources generator parameter. Starting with ScalaPB 1.x, this output cannot be compiled with Scala 2, including with -Xsource:3; ScalaPB 0.11.x supported that combination. When cross-building, enable this option only for the Scala 3 build. See the Scala 3 settings and migration guidance.

  • Use public_constructor_parameters to make constructor parameters public, including defaults and TypeMappers. This is helpful for automated schema derivation with e.g. magnolia when trying to also derive default fields by using the compiler flag -Yretain-trees. Without this flag, the companion object's _typemapper_* fields are private.

Custom base traits for messages​

Note: this option is available in ScalaPB 0.6.1 and later.

ScalaPB allows you to specify custom base traits to a generated case class. This is useful when you have a few messages that share common fields and you would like to be able to access those fields through a single trait.

Example:

import "scalapb/scalapb.proto";

message CustomerWithPhone {
option (scalapb.message).extends = "com.thesamet.pb.BaseCustomer";

optional string customer_id = 1;
optional string name = 2;
optional string phone = 3;
}

In your code, define the base trait BaseCustomer and include any subset of the fields:

package com.thesamet.pb

trait BaseCustomer {
def customerId: Option[String]
def name: Option[String]
}

You can specify any number of base traits for a message.

It is also possible to make the generated companion classes extend a class or trait, by using the companion_extends option. For example:

message MyMessage {
option (scalapb.message).extends = "MySuperClass";
option (scalapb.message).companion_extends = "MySuperCompanionClass";
int32 n = 1;
}

Will generate a case class that extends MySuperClass, and the companion object will extend MySuperCompanionClass.

Custom base traits for sealed oneofs​

Since 0.9.0, you can use sealed_oneof_extends to define one or more base traits for a generated SealedOneof.

Since 0.11.16, you can also add base traits to the empty case object using sealed_oneof_empty_extends.

Use the following options:

message MyEither {
option (scalapb.message).sealed_oneof_extends = "MyBaseTrait";
option (scalapb.message).sealed_oneof_empty_extends = "MyEmptyTrait";

oneof sealed_value {
Left left = 1;
Right right = 2;
}
}

As of ScalaPB 0.11.11 you may also use following option to make the generated sealed oneof trait universal. It may be useful when your sealed oneof variants are value-classes (e.g. extends AnyVal)

trait MyBaseUniversalTrait extends Any
message Left {
option (scalapb.message).extends = "AnyVal";
string error = 1;
}

message Right {
option (scalapb.message).extends = "AnyVal";
int32 value = 1;
}

message MyEither {
option (scalapb.message) = {
sealed_oneof_extends: ["Any", "MyBaseUniversalTrait"]
};

oneof sealed_value {
Left left = 1;
Right right = 2;
}
}

Custom base traits for sealed oneofs companion objects​

Note: this option is available in ScalaPB 0.11.11 and later.

Use the following option to define one or more base traits for a generated SealedOneof companion object:

message MyEither {
option (scalapb.message).sealed_oneof_companion_extends = "MyBaseTrait";
oneof sealed_value { /* ... */ }
}

Custom base traits for enums​

In a similar fashion to custom base traits for messages, it is possible to define custom base traits for enum types, for the companion objects of enum types and even for specific values.

For example:

syntax = "proto2";

package enum_example;

import "scalapb/scalapb.proto";

enum MyEnum {
option (scalapb.enum_options).extends = "example.EnumOptions.EnumBase";
option (scalapb.enum_options).companion_extends = "example.EnumOptions.EnumCompanionBase";
Unknown = 0;
V1 = 1 [(scalapb.enum_value).extends = "example.EnumOptions.ValueMixin"];
V2 = 2;
}

The generated code will look something like this:

sealed trait MyEnum extends GeneratedEnum
with example.EnumOptions.EnumBase {
/* ... */
}

object MyEnum extends GeneratedEnumCompanion[MyEnum]
with example.EnumOptions.EnumCompanionBase {
case object Unknown extends MyEnum { /* ... */ }

case object V1 extends MyEnum
with example.EnumOptions.ValueMixin { /* ... */ }

case object V2 extends MyEnum { /* ... */ }

/* ... */
}

Custom names​

Sometimes it may be useful to manually specify the name of a field in the generated code. For example, if you have a field named hash_code, then the camel-case version of it would be hashCode. Since that name would conflict with the hashCode() method we inherit from Java, ScalaPB issues an error. You can tell ScalaPB to use an alternative name by using the scala_name option:

optional string hash_code = 1 [(scalapb.field).scala_name = "myHashCode"];

It is also possible to customize the Scala name of an enum value:

enum MyEnum {
DEFAULT = 0;
FOO = 1 [(scalapb.enum_value).scala_name = "Bar"];
}

The same customization can be applied to oneof fields:

oneof notify {
option (scalapb.oneof).scala_name = "myNotify";

string foo = 1;
int32 bar = 2;
}

Adding annotations​

Since ScalaPB 0.6.3, you can add annotations to the generated case classes like this:

message BarMessage {
option (scalapb.message).annotations = "@mypackage.CustomAnnotation";
option (scalapb.message).annotations = "@mypackage.CustomAnnotation1";
option (scalapb.message).annotations = "@mypackage.CustomAnnotation2";
}

In ScalaPB 0.7.0, you can add annotations to the companion object of a message and to individual fields:

message BarMessage {
option (scalapb.message).companion_annotations = "@mypackage.AnotherAnnotation2";

optional string x = 1 [
(scalapb.field).annotations = '@deprecated("Will be gone", "1.0")'
];
}

In ScalaPB 0.10.9, you can also add annotations to the auto generated unknownFields field:

message BarMessage {
option (scalapb.message).unknown_field_annotations = "@annotation1";
}

In ScalaPB 0.11.4, you can also add annotations to the enum values and the Unrecognized case class:

enum BarEnum {
// every value will have the annotation added.
option (scalapb.enum_options).base_annotations = "@annotation1";
// only known values (case objects) will have the annotation added.
option (scalapb.enum_options).recognized_annotations = "@annotation2";
// only the unrecognized case class will have the annotation added.
option (scalapb.enum_options).unrecognized_annotations = "@annotation3";
// only this value (case object) will have the annotation added.
BarValue = 1 [(scalapb.enum_value).annotations = "@annotation4"];
}

Adding derives clause​

In ScalaPB 0.11.14, it is possible to add a derives clause to generated messages and sealed oneofs:

message Foo {
option (scalapb.message).derives = "yourpkg.Show";
// fields...
}

message Expr {
option (scalapb.message).sealed_oneof_derives = "yourpkg.Show";
oneof sealed_value {
...
}
}

Binary string UTF-8 validation​

For proto2 and proto3 schemas, ScalaPB validates UTF-8 when parsing ordinary binary string fields by default. To opt into the protobuf Java schema policy:

import "scalapb/scalapb.proto";
option (scalapb.options).use_schema_utf8_validation = true;

This option can also be inherited from package-scoped ScalaPB options. Set it to false in a proto2 or proto3 file to retain strict validation. Regenerate your Scala sources after changing the option; already-generated parsers are unaffected.

With the option enabled, proto2 strings validate when java_string_check_utf8 is true, and proto3 strings validate by default. For Editions schemas, the generator always follows the schema policy, regardless of this option. It uses the Java descriptor needsUtf8Check() API to resolve inherited features.utf8_validation settings and Java-specific overrides.

String map keys and values always validate, including in nonvalidating files. Fields generated with lazy_utf8_string_fields follow the same policy; nonvalidating lazy fields keep the original bytes. The policy applies equally to singular, repeated, oneof, and custom-mapped strings.

Nonvalidating eager fields decode to Scala String, replacing malformed UTF-8 with replacement characters. The original malformed bytes are lost before any custom type mapper runs. Reserializing is not a byte-preserving round trip, and replacement grouping can differ between JVM, JavaScript, and Native decoders. Use a bytes field (wire-compatible with string) when you need to retain arbitrary bytes, or enable lazy string fields to preserve the bytes of nonvalidating string fields. Accessing a lazy field does not discard its stored bytes. Valid Unicode is unaffected by this option.

This option controls generated binary message parsers. It does not change text format parsing, JSON support, serialization, or extension accessors (which decode strings from their stored unknown-field bytes). For the upstream Java policy and its string-only versus dual representation distinction, see UTF-8 Validation in Java.

JavaScript and Native require protobuf-runtime-scala 0.9.0 or newer for strict malformed-input rejection (included by this release). The 0.9.0 upgrade also makes the deprecated ByteString.bytes return a copy rather than exposing its backing array; use toByteArray(). See the runtime's 0.9.0 release notes for the stable-path source incompatibility and other validation fixes.

Moved sections​

The following sections now have their own guides. These links also keep older bookmarks working.

Package-scoped options​

See package-scoped options.

Flat packages and dependencies​

See flat packages and dependencies.

Publishing package-scoped options​

See publishing package-scoped options.

Disabling package-scoped options processing​

See disabling package-scoped options processing.

Auxiliary options​

See auxiliary options.

Making third-party models package-private​

See making third-party models package-private.

Primitive wrappers​

See primitive wrappers.

Custom types​

See custom types.

Lazy String Fields​

See lazy string fields.

Using lazy fields​

See using lazy fields.

Equality and collections​

See equality and collections.

UTF-8 validation and Java conversions​

See utf-8 validation and java conversions.

When to use lazy strings​

See when to use lazy strings.

Message-level custom type and boxing​

See message-level custom type and boxing.

Custom types on maps​

See custom types on maps.

Custom collection types​

See custom collection types.