Protocol Buffers Kotlin Core: Introduction and Implementation Details
dependencies {
implementation 'com.google.protobuf:protobuf-java:3.15.8'
implementation 'com.google.protobuf:protobuf-kotlin:3.15.8'
implementation 'com.google.protobuf:protoc-gen-javalite:3.15.8'
implementation 'com.google.protobuf:protoc-gen-kotlin:3.15.8'
}
protobuf
syntax = "proto3";
message Person {
string name = 1;
int32 age = 2;
repeated string hobbies = 3;
}
protoc --kotlin_out=./src/main/kotlin ./src/main/proto/person.proto
kotlin
import com.example.PersonProto.Person
fun main() {
val person = Person.newBuilder()
.setName("John Doe")
.setAge(25)
.addHobbies("Reading")
.addHobbies("Gaming")
.build()
val serializedData = person.toByteArray()
val deserializedPerson = Person.parseFrom(serializedData)
println("Name: ${deserializedPerson.name}")
println("Age: ${deserializedPerson.age}")
println("Hobbies: ${deserializedPerson.hobbiesList}")
}