Google added support for Kotlin to its open source Protocol Buffers project, which is able to translate a proto definition into an idiomatic Domain Specific Language (DSL) leveraging Kotlin advanced syntax features.
Thanks to Kotlin's interop with Java, Kotlin programs could already work with Protocol Buffers by simply using the classes that the Protocol Buffers compiler is able to generate for the Java language. Direct support for Kotlin in the proto compiler, thus, does not introduce any previously unavailable capabilities. Yet, it is highly interesting thanks to the way it leverages Kotlin advanced syntax to generate idiomatic Kotlin bindings using a set of factory methods that constitute a nice DSL.
The Kotlin version uses Kotlin type-safe builders, which makes it concise and removes the need to explicitly call a build method. Note that this works with both the proto compiler’s standard and "proto lite" modes, the latter generating smaller, higher performance classes which are more suitable for Android.
The benefit of using a DSL resides in the generated code using almost no sugaring code and thus being more expressive, with a declarative look to it. 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.
In its announcement, Google also illustrates how Kotlin protocol buffers can be easily integrated with Kotlin gRPC, which was open sourced last year, and provided some basic client/server sample projects.
While Kotlin bindings for Protocol Buffers are a nice addition, they are still relatively new and not exempt from potential issues. In particular, if your program uses a complex proto model, you might want to make sure it does not hit into a known Kotlin compiler bug, or that you can tackle it by increasing the memory reserved to it.
As an alternative to using Google's own proto bindings for Kotlin, you could look into Square's Wire, an open-source, independent Protocol Buffers implementation from Square that specifically targets the Java/Android platform and also provides idiomatic Kotlin bindings as well as integration with gRPC.