Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
166: Serializing to Protocol Buffers with Kotlin
You've likely spent most of your career treating JSON as the default for everything. It's readable, every language speaks it, and it's easy to debug. But as you move into high-throughput internal services or mobile apps where bandwidth is a premium, JSON becomes a liability. It's bloated and slow to parse. That's where Protocol Buffers (Protobuf) come in. However, if you just follow the standard tutorials, you'll likely end up with a Kotlin codebase that feels like it was written in 2012.
The Builder Pattern Tax
The naive way to use Protobuf in Kotlin is to use the official protoc compiler to generate Java classes. I've seen this in countless legacy projects. You define your .proto file, run the compiler, and suddenly your project is filled with these massive, rigid Java classes. To create a simple UserEvent object, you're forced into the Java Builder pattern:
// The "Java-style" way in Kotlin
val event = UserEvent.newBuilder()
.setUserId("user-123")
.setEventType(EventType.CLICK)
.setTimestamp(System.currentTimeMillis())
.build()
It works, but it's exhausting. You're fighting the language. Kotlin gives us named arguments and data classes specifically so we can stop writing builders. When you use the generated Java code, you lose Kotlin's null safety guarantees, and your code becomes a wall of .setSomething() calls. It's an ergonomics nightmare that makes the codebase feel clunky.
Embracing Kotlin Types
The better way, especially for Kotlin-to-Kotlin communication, is to use kotlinx.serialization. Instead of letting a separate compiler generate your classes, you define your data models as standard Kotlin data classes and annotate them. You're essentially telling Kotlin, "Treat this class as a Protobuf message."
Take a look at how we'd handle that same UserEvent:
@Serializable
data class UserEvent(
@ProtoNumber(1) val userId: String,
@ProtoNumber(2) val eventType: EventType,
@ProtoNumber(3) val timestamp: Long
)
// Serialization is now a one-liner
val bytes = ProtoBuf.encodeToByteArray(UserEvent("user-123", EventType.CLICK, 1625000000L))
val decoded = ProtoBuf.decodeFromByteArray<UserEvent>(bytes)
Notice the @ProtoNumber annotations. This is the most critical part. In Protobuf, the field name doesn't actually exist in the binary stream; only the field number does. By explicitly tagging your properties, you ensure that if you rename userId to accountId in your code, you don't break compatibility with the data already stored in your database or being sent by other services.
When the Trade-off Bites Back
I want to be honest with you: kotlinx.serialization is fantastic for developer velocity, but it's not a 1:1 replacement for the official protoc toolchain if you're working in a polyglot environment. If your Kotlin service needs to communicate with a Go service or a C++ backend, the official .proto file is your "single source of truth."
The kotlinx.serialization approach is "schema-less" in the sense that the Kotlin code is the schema. If you need a hard contract that multiple teams across different languages must sign off on, you'll have to go back to the generated classes—or use a plugin that generates Kotlin-friendly wrappers around the Java code. But for most internal Kotlin microservices? The boilerplate of the Java builders is a cost you simply shouldn't pay.
📋 Practical Task
Implement a High-Efficiency Telemetry Packet
You are building a telemetry system for a drone that sends packets of data back to a ground station. Currently, the system uses JSON, and the packets are too large, causing latency. Your task is to convert the telemetry system to use kotlinx.serialization with Protocol Buffers.
Requirements:
- Create a
TelemetryPacketdata class annotated for Protobuf serialization. - The packet must include:
droneId(String),batteryLevel(Double),gpsCoordinates(a nested data class withlatandlon), and astatus(an Enum:IDLE,FLYING,EMERGENCY). - Ensure every field has a unique
@ProtoNumberto maintain backward compatibility. - Write a small function
serializeTelemetry(packet: TelemetryPacket): ByteArraythat returns the binary representation of the packet. - Verify your implementation by encoding a packet and then decoding it back to ensure the data remains intact.
There are no comments for now.