🌐
Protocol Buffers
protobuf.dev › getting-started › kotlintutorial
Protocol Buffer Basics: Kotlin | Protocol Buffers Documentation
Our example is a set of command-line applications for managing an address book data file, encoded using protocol buffers. The command add_person_kotlin adds a new entry to the data file.
🌐
Protocol Buffers
protobuf.dev › reference › kotlin › kotlin-generated
Kotlin Generated Code Guide | Protocol Buffers Documentation
The output file is chosen by concatenating the parameter to --kotlin_out=, the package name (with periods [.] replaced with slashes [/]), and the suffix Kt.kt file name. So, for example, let’s say you invoke the compiler as follows:
Discussions

Setting up Protobuf + Kotlin in Android Studio 2023 - Stack Overflow
I spend hours on just setting up Protobuf with Kotlin in Android Studio. The endgoal is just that my proto files are compiled in Kotlin and that I can use them in my project. I have an example proj... More on stackoverflow.com
🌐 stackoverflow.com
How can I generate protobuf in Kotlin for Android applications? - Stack Overflow
Can anyone provide a link for a ... generate Protobuf sample to Kotlin? ... Save this answer. ... Show activity on this post. I've used both square/wire and io.grpc libraries to communicate with a gRPC service. The problem with the wire is that it does not support the proto3 version yet. ... Here, I'll provide you an example of how to ... More on stackoverflow.com
🌐 stackoverflow.com
Protobuf serialization in kotlin

Are you intending to align with kotlinx.serialization? In the general case, I would advise doing so - this is the emerging standard for Kotlin serialization which spans serialization formats (JSON, CBOR, and Protobuf first supported) and is designed to work with multi-platform.

More on reddit.com
🌐 r/Kotlin
12
6
April 8, 2019
java - How to setup protobuf in kotlin/android studio? - Stack Overflow
Also see protobuf-gradle-plugin (the Kotlin/GRPC example there isn't for Android). More on stackoverflow.com
🌐 stackoverflow.com
🌐
Jsontotable
jsontotable.org › blog › protobuf › kotlin-protobuf-guide
How to Use Protocol Buffers in Kotlin - Complete Guide with Examples | JSON to Table Converter
This guide shows you how to use Protocol Buffers in Kotlin projects, covering both Android and JVM applications. If you're new to Protocol Buffers, check out our Protobuf vs JSON comparison first.
🌐
Kotlin
kotlinlang.org › api › kotlinx.serialization › kotlinx-serialization-protobuf › kotlinx.serialization.protobuf › -proto-buf
ProtoBuf | kotlinx.serialization – Kotlin Programming Language
In proto3, fields by default are implicitly optional, so corresponding Kotlin properties have to be nullable and have a default value null. In proto3, all lists use packed encoding by default. To be able to decode them, annotation ProtoPacked should be used on all properties with type List. // Serialize to ProtoBuf bytes.
🌐
StackHawk
stackhawk.com › stackhawk, inc. › tooling guides › securing your kotlin application: preventing broken auth
Kotlin & Protobuf Tips & Tricks
September 18, 2025 - The Protobuf Gradle Plugin now comes with built-in protoc compiler support for Kotlin. Unlike Java, the plugin does not enable Kotlin generation by default. Here’s an example Protobuf Gradle Plugin config to generate non-GRPC Kotlin:
🌐
Medium
medium.com › digitalfrontiers › a-dance-with-protocols-kotlin-spring-and-protocol-buffers-in-action-ded306546070
A Dance with Protocols: Kotlin, Spring and Protocol Buffers in Action | by Benedikt Jerat | Digital Frontiers — Das Blog | Medium
February 26, 2019 - Take a look at the protobuf-gradle-plugin GitHub project for an example gradle file to set everything up for the Protobuf Lite Runtime. But don’t let the size of the generated classes put you off, because it’s actually very easy to work with them. For each message type, a Builder class is generated with which instances can be created: One of the sad points of missing native Kotlin support: No data classes are created, with which one can work so comfortably in Kotlin due to named parameter instantiation, copy constructor and auto-generated equals, hashCode and toString methods.
🌐
Medium
medium.com › @zekromvishwa56789 › setting-up-protocol-buffers-in-an-android-project-8f7bad31981f
Setting Up Protocol Buffers in an Android Project | by Vishwajith Shettigar | Medium
December 8, 2024 - To do this, simply skip Step 1 and add the Protobuf dependencies and configurations to the app module's build.gradle file wherever they are specified for the model module. Below, I’ve included a link to a GitHub repository where the Protobuf setup is done directly in the app module. Open your Android project in Android Studio. ... Go to File > New > New Module. Select Java or Kotlin Library and click Next.
Top answer
1 of 3
4

You are in a good way, but, there is some stuff missing:

The gradle code I'll share is written in Kotlin, just in case. If you can convert your grade files to Kotlin, nice, if not you have to convert them to groovy.

  1. The first thing to check is if you have the proto folder in the right path, it should be in
root->app->src->main->proto
  1. In the project gradle make sure to have the plugin applied
id("com.google.protobuf") version "0.8.15" apply false
  1. In the app gradle, make sure to have the following.
import com.google.protobuf.gradle.*

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
    id("com.google.protobuf")
}

The dependencies:

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.2")
    implementation("com.google.protobuf:protobuf-kotlin:3.21.2")
    implementation("io.grpc:grpc-stub:1.52.0")
    implementation("io.grpc:grpc-protobuf:1.52.0")
    implementation("io.grpc:grpc-okhttp:1.52.0")

    implementation("com.google.protobuf:protobuf-java-util:3.21.7")
    implementation("com.google.protobuf:protobuf-kotlin:3.21.2")
    implementation("io.grpc:grpc-kotlin-stub:1.3.0")

And the protobuf task:

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:${rootProject.ext["protobufVersion"]}"
    }
    plugins {
        id("java") {
            artifact = "io.grpc:protoc-gen-grpc-java:${rootProject.ext["grpcVersion"]}"
        }
        id("grpc") {
            artifact = "io.grpc:protoc-gen-grpc-java:${rootProject.ext["grpcVersion"]}"
        }
        id("grpckt") {
            artifact = "io.grpc:protoc-gen-grpc-kotlin:${rootProject.ext["grpcKotlinVersion"]}:jdk8@jar"
        }
    }
    generateProtoTasks {
        all().forEach {
            it.plugins {
                id("java") {
                    option("lite")
                }
                id("grpc") {
                    option("lite")
                }
                id("grpckt") {
                    option("lite")
                }
            }
            it.builtins {
                id("kotlin") {
                    option("lite")
                }
            }
        }
    }
}

These are the versions I'm using:

ext["grpcVersion"] = "1.47.0"
ext["grpcKotlinVersion"] = "1.3.0" // CURRENT_GRPC_KOTLIN_VERSION
ext["protobufVersion"] = "3.21.2"
ext["coroutinesVersion"] = "1.6.2"

Having that your project should generate the code based on your proto files.

For further reference, I recently build this Android App based on Kotlin + gRPC: https://github.com/wilsoncastiblanco/notes-grpc

2 of 3
2

Maybe too little too late, but the answer here worked for me using Android Studio Electric Eel | 2022.1.1 Patch 1--with the exception of the protobuf section. I had to change it from:

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.20.1"
    }
    plugins {
        javalite {
            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
        }
    }
    generateProtoTasks {
        all().each { task ->
            java {
                option 'lite'
            }
            kotlin {
                option 'lite'
            }
        }
    }
}

To:

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.20.1"
    }
    plugins {
        javalite {
            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
        }
    }

    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option 'lite'
                }
                kotlin {
                    option 'lite'
                }
            }
        }
    }
}

Notice the subtle difference in the generateProtoTasks. Just make sure you drop your .proto file into /src/main/proto in your project and you should be good to go.

Find elsewhere
🌐
InfoQ
infoq.com › news › 2021 › 12 › protocol-buffers-kotlin-dsl
Google Protocol Buffers Support Idiomatic Kotlin Bindings - InfoQ
December 31, 2021 - Google has shown a simple example of a protocol buffers message representing a series of dice rolls to make that obvious: /* Protobuf definition: */ message DiceSeries { message DiceRoll { int32 value = 1; // value of this roll, e.g. 2..12 string nickname = 2; // string nickname, e.g. "snake eyes" } repeated DiceRoll rolls = 1; } // Kotlin bindings usage: val series = diceSeries { rolls = listOf( diceRoll { value = 5 }, diceRoll { value = 20 nickname = "critical hit" } ) } The Java bindings for the same message definition would create instead a couple of classes that you would need to glue together using the flexible but verbose builder pattern to the same aim as the code shown above.
🌐
SSOJet
ssojet.com › serialize-and-deserialize › serialize-and-deserialize-protobuf-in-kotlin
Serialize and Deserialize Protobuf in Kotlin | Serialize and Deserialize Data in Programming Languages
Handling data serialization and deserialization efficiently is crucial for any application dealing with inter-process communication or persistent storage. This guide dives into using Protocol Buffers (Protobuf) with Kotlin, demonstrating how to define your data structures and implement the serialization and deserialization logic.
🌐
Medium
medium.com › mobile-app-development-publication › android-protobuf-in-kotlin-a1c33014a4e2
Android Protobuf in Kotlin with example app | by Elye - A Dev By Grace | Mobile App Development Publication | Medium
February 22, 2018 - Android Protobuf in Kotlin with example app Using Kotlin to access Protobuf generated code is not feasible as pointed out in my previous blog. But cheer up, there’s a workaround, if you just really …
Top answer
1 of 1
2

I've used both square/wire and io.grpc libraries to communicate with a gRPC service. The problem with the wire is that it does not support the proto3 version yet.

https://github.com/square/wire/issues/279

Here, I'll provide you an example of how to start with io.grpc.

Suppose that there is a gRPC service which sums up the stream of numbers you're sending to it. Its proto file is gonna be something like:

accumulator.proto

syntax = "proto3";

package accumulator;

service Accumulator {
    rpc NumberStream (stream NumberRequest) returns (stream AccumulateReply) {
    }
}

message NumberRequest {
    int32 number = 1;
}

message AccumulateReply {
    int64 sumUp = 1;
}

You should put this file under /src/main/proto/ directory of the project.

Now it's time to add the required dependencies to build.gradle file. Note that it uses kapt to generate codes.


App Level's build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.protobuf'
apply plugin: 'kotlin-kapt'

android {
    
    ... others

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8
    }
}

protobuf {
    protoc { artifact = 'com.google.protobuf:protoc:3.10.0' }

    plugins {
        javalite { artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0" }
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:1.25.0' // CURRENT_GRPC_VERSION
        }
    }

    generateProtoTasks {
        all().each { task ->
            task.plugins {
                javalite {}
                grpc { // Options added to --grpc_out
                    option 'lite'
                }
            }
        }
    }
}

dependencies {
    ... other dependencies

    // ------- GRPC
    def grpc_version = '1.25.0'
    implementation "io.grpc:grpc-android:$grpc_version"
    implementation "io.grpc:grpc-okhttp:$grpc_version"
    implementation "io.grpc:grpc-protobuf-lite:$grpc_version"
    implementation "io.grpc:grpc-stub:$grpc_version"

    // ------- Annotation
    def javax_annotation_version = '1.3.2'
    implementation "javax.annotation:javax.annotation-api:$javax_annotation_version"
}

Project Level's build.gradle

buildscript {

    repositories {
        google()
        jcenter()
    }

    dependencies {
        ... others

        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.10'
    }
}

Here is a class that encapsulates stream activities with the server. It returns received values through a callback:

AccumulatorHandler.kt

import android.content.Context
import io.grpc.ManagedChannel
import io.grpc.android.AndroidChannelBuilder
import io.grpc.stub.ClientCallStreamObserver
import io.grpc.stub.StreamObserver
import accumulator.AccumulatorOuterClass
import java.util.concurrent.Executors


/**
 * @author aminography
 */
class AccumulatorHandler constructor(
    private val context: Context,
    private val endPoint: String
) {

    var callback: AccumulatorCallback? = null

    private var managedChannel: ManagedChannel? = null

    private var requestObserver: StreamObserver<AccumulatorOuterClass.NumberRequest>? = null

    private val responseObserver: StreamObserver<AccumulatorOuterClass.AccumulateReply> =
        object : StreamObserver<AccumulatorOuterClass.AccumulateReply> {

            override fun onNext(value: AccumulatorOuterClass.AccumulateReply?) {
                callback?.onReceived(value.sumUp)
            }

            override fun onError(t: Throwable?) {
                callback?.onError(t)
            }

            override fun onCompleted() {
                callback?.onCompleted()
            }
        }

    fun offer(number: Int) {
        initChannelIfNeeded()
        requestObserver?.onNext(
            AccumulatorOuterClass.NumberRequest.newBuilder()
                .setNumber(number)
                .build()
        )
    }

    fun offeringFinished() {
        requestObserver?.onCompleted()
    }

    private fun initChannelIfNeeded() {
        if (managedChannel == null) {
            managedChannel = AndroidChannelBuilder.forTarget(endPoint)
                .context(context)
                .usePlaintext()
                .executor(Executors.newSingleThreadExecutor())
                .build()
        }
        if (requestObserver == null) {
            requestObserver = AccumulatorGrpc.newStub(managedChannel)
                .withExecutor(Executors.newSingleThreadExecutor())
                .numberStream(responseObserver)
        }
    }

    fun release() {
        (requestObserver as? ClientCallStreamObserver<*>)?.cancel("Cancelled by client.", null)
        requestObserver = null

        managedChannel?.shutdown()
        managedChannel = null

        callback = null
    }

    interface AccumulatorCallback {
        fun onReceived(sum: Long)
        fun onError(t: Throwable?)
        fun onCompleted()
    }

}

In order to test it, I've written an activity class to show its usage in a simple manner:

MyActivity.kt

/**
 * @author aminography
 */
class MyActivity: AppCompatActivity, AccumulatorHandler.AccumulatorCallback {

    private var accumulatorHandler: AccumulatorHandler? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        accumulatorHandler = AccumulatorHandler(applicationContext, "http://...")
        accumulatorHandler.callback = this

        for (number in 1..10){
            accumulatorHandler.offer(number)
        }
        accumulatorHandler.offeringFinished()
    }

    override fun onReceived(sum: Long) {
        Toast.makeText(this, "onReceived: $sum", Toast.LENGTH_SHORT).show()
    }

    override fun onError(t: Throwable?) {
        Toast.makeText(this, "onError: $t", Toast.LENGTH_SHORT).show()
        accumulatorHandler.release()
    }

    override fun onCompleted() {
        Toast.makeText(this, "onCompleted", Toast.LENGTH_SHORT).show()
        accumulatorHandler.release()
    }
}
🌐
Reddit
reddit.com › r/kotlin › protobuf serialization in kotlin
r/Kotlin on Reddit: Protobuf serialization in kotlin
April 8, 2019 -

Hello, want to use protobuf to serialize a large string object to be stored in realm, as of now using JSON which is causing huge object memory. But not sure how can I use protobuf to achieve this as there are very little online examples that isn't relevant to my usecase. protobuf uses schema (.proto) file and serialize this file so that we can use it but in my case I will get string from response that needs serialization, any help would be much appreciated.

🌐
GitHub
github.com › open-toast › protokt
GitHub - open-toast/protokt: Protobuf compiler and runtime for Kotlin · GitHub
Wrapper types that wrap protobuf primitives are non-null. For example, java.util.UUID wrapping bytes generates val uuid: UUID. Conversion from the wire default value (e.g. empty bytes) to the Kotlin type is deferred until the property is accessed, so a converter that rejects default values (like UuidBytesConverter which requires exactly 16 bytes) will throw at access time rather than at deserialization time:
Starred by 167 users
Forked by 16 users
Languages   Kotlin
Top answer
1 of 3
13

One cannot add *.proto files into Java or Kotlin source directories ...
For Android use protobuf-lite; the configuration looks about like this:

plugins {
    id 'com.android.application' version "8.11.1" apply false
    id 'com.google.protobuf' version "0.9.5" apply false
}

Module-level build.gradle:

plugins {
    id "com.android.application"
    id "com.google.protobuf"
}

android {
    sourceSets {
        main {
            java {
                srcDirs += "build/generated/source/proto/main/java"
            }
            kotlin {
                srcDirs += "build/generated/source/proto/main/kotlin"
            }
            proto {
                srcDir "src/main/proto" // default value
            }
        }
    }
}

dependencies {
    implementation "com.google.protobuf:protobuf-javalite:3.20.1"
    implementation "com.google.protobuf:protobuf-kotlin-lite:3.20.1"
}

There's also a protoc compiler and protoc-gen-javalite generator available:

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.20.1"
    }
    plugins {
        javalite {
            artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
        }
    }
    generateProtoTasks {
        all().each { task ->
            java {
                option "lite"
            }
            kotlin {
                option "lite"
            }
        }
    }
}

Also see protobuf-gradle-plugin (the Kotlin/GRPC example there isn't for Android).

2 of 3
5

I configured protobuf like this:

app/build.gradle.kts

plugins {
    ...
    id("com.google.protobuf") version "0.9.4"
}

android {}

dependencies {
    ...
    implementation("com.google.protobuf:protobuf-javalite:3.18.0")
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.19.4"
    }

    generateProtoTasks {
        all().configureEach {
            builtins {
                id("java") {
                    option("lite")
                }
            }
        }
    }
}
🌐
AnyMind Group
anymindgroup.com › news › tech-blog › 15380
[Tech Blog] A quick guide into Protobuf | AnyMind Group
May 12, 2022 - You can see that setup is pretty simple, the only things we need to tune up are plugins, one dependency for kotlin generated code, compiler bundle and output languages. Firstly take a look at proto file. Example proto file describes an instagram profile’s followers country breakdown.
🌐
GitHub
github.com › cretz › pb-and-k
GitHub - cretz/pb-and-k: Kotlin Code Generator and Runtime for Protocol Buffers · GitHub
This was done because Kotlin does not handle array fields in data classes predictably and it wasn't worth overriding equals and hashCode every time. Regardless of optimize_for options, the generated code is always the same. Each message has a protoSize field that lazily calculates the size of the message when first invoked. Also, each message has the plus operator defined which follows protobuf merge semantics.
Starred by 143 users
Forked by 15 users
Languages   Kotlin
🌐
GitHub
github.com › jdekim43 › kotlin-protobuf
GitHub - jdekim43/kotlin-protobuf: Protobuf Generator for Kotlin · GitHub
plugins { kotlin("jvm") version "1.9.23" kotlin("plugin.serialization") version "1.9.23" //optional id("com.google.protobuf") version "0.9.4" } sourceSets { main { proto { srcDir(File(project.projectDir, "src/main/proto")) } } } protobuf { plugins { //If you want without kotlinx-serialization.
Author   jdekim43
🌐
Google Developers
developers.googleblog.com › google for developers blog › announcing kotlin support for protocol buffers
Announcing Kotlin support for protocol buffers - Google Developers Blog
November 1, 2021 - For examples that can be deployed ... platform) check out: grpc-hello-world-gradle, grpc-hello-world-streaming (server push), or grpc-hello-world-bidi-streaming (bi-directional streaming)....