Protocol are Google's language-neutral, platform-neutral, extensible for serializing structured data. It is a popular choice for serialization formats; therefore, there is built-in support for it in the kotlinx.serialization project. Protobuf is a binary format. Since Protobuf relies on serial IDs of fields, called tags, you have to provide the information, using the @SerialId annotation. Let’s enhance the Student class used earlier to use it with the Google serialization:
@Serializable
data class Student(
@SerialId(1) val firstName: String,
@SerialId(2) val lastName: String,
@SerialId(3) val score: Int,
@SerialId(4) @Optional val penalties: Int = 0
)
Having this done, marshaling to and from binary Protobuf is quite trivial and follows the same pattern already seen for JSON:
val proto = ProtoBuf().dump(Student.serializer...