• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // This file was automatically generated from formats.md by Knit tool. Do not edit.
2 package example.exampleFormats08
3 
4 import kotlinx.serialization.*
5 import kotlinx.serialization.protobuf.*
6 
7 // The outer class
8 @OptIn(ExperimentalSerializationApi::class)
9 @Serializable
10 data class Data(
11     @ProtoNumber(1) val name: String,
12     @ProtoOneOf val phone: IPhoneType?,
13 )
14 
15 // The oneof interface
16 @Serializable sealed interface IPhoneType
17 
18 // Message holder for home_phone
19 @OptIn(ExperimentalSerializationApi::class)
20 @Serializable @JvmInline value class HomePhone(@ProtoNumber(2) val number: String): IPhoneType
21 
22 // Message holder for work_phone. Can also be a value class, but we leave it as `data` to demonstrate that both variants can be used.
23 @OptIn(ExperimentalSerializationApi::class)
24 @Serializable data class WorkPhone(@ProtoNumber(3) val number: String): IPhoneType
25 
26 @OptIn(ExperimentalSerializationApi::class)
mainnull27 fun main() {
28   val dataTom = Data("Tom", HomePhone("123"))
29   val stringTom = ProtoBuf.encodeToHexString(dataTom)
30   val dataJerry = Data("Jerry", WorkPhone("789"))
31   val stringJerry = ProtoBuf.encodeToHexString(dataJerry)
32   println(stringTom)
33   println(stringJerry)
34   println(ProtoBuf.decodeFromHexString<Data>(stringTom))
35   println(ProtoBuf.decodeFromHexString<Data>(stringJerry))
36 }
37