.encodeToByteArray()
The .encodeToByteArray()
method is provided by the kotlinx.serialization
library and is used to serialize and convert the given data to a byte array. This method is the inverse of the .decodeFromByteArray()
method.
Syntax
fun <T> BinaryFormat.encodeToByteArray(value: T): ByteArray
<T>
: The type of data to be converted.value
: The data to be converted.BinaryFormat
: An interface that allows conversions to and fromByteArray
via the.encodeToByteArray()
and.decodeFromByteArray()
methods. An example ofBinaryFormat
isProtoBuf
.
Example
The below code demonstrates the use of .encodeToByteArray()
:
import kotlinx.serialization.*import kotlinx.serialization.protobuf.ProtoBuf@Serializabledata class Course(val name: String, val description: String)fun main() {val course = Course("Learn Kotlin", "The expressive, open-source programming language developed by JetBrains.")val courseToByteArray = ProtoBuf.encodeToByteArray(course)println("My course in byte array: $courseToByteArray")}
The output of the above code is:
My course in byte array: [B@21588809
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.