On November 1, Google announced its support for Protocol Buffers in Kotlin, further deepening its investment in Kotlin, a programming language.

Protocol Buffers (ProtocolBuffer/protobuf) is a data description language developed by Google. It can serialize structured data similar to XML and can be used for data storage, communication protocols, etc.

Last year, Google announced Kotlin support for gRPC, an open source remote procedure call (RPC) framework that provides support for thousands of Google microservices. Google said that it will invest heavily in the Kotlin language and ecosystem in the future. Android development will give priority to Kotlin, and the construction of back-end services will also use Kotlin as much as possible. This is due to their expressiveness, security and two-way interaction with Java. Operational favorite.

Now, developers can use the newly built-in Kotlin support in the proto compiler to generate the idiomatic Kotlin Domain Specific Language (DSL).

For example, this is a simple protocol buffer message, representing a roll of the dice:

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;
}

It looks like this in Java:

DiceSeries series = DiceSeries.newBuilder()
    .addRoll(DiceRoll.newBuilder()
        .setValue(5))
    .addRoll(DiceRoll.newBuilder()
        .setValue(20)
        .setNickname("critical hit"))
    .build()

In this version, protos provides a set of expressive DSL construction methods to make this code more concise and elegant in Kotlin. Below is the dice code written using the new Kotlin prototype binding:

val series = diceSeries {
  rolls = listOf(
    diceRoll { value = 5 },
    diceRoll {
      value = 20
      nickname = "critical hit"
    }
  )
}

It can be seen that the Kotlin version uses the Kotlin type safe builder to make the code more concise, and there is no need to explicitly call the build method.


snakesss
1.1k 声望244 粉丝

SegmentFault 思否编辑,欢迎投稿优质技术资讯!