.encodeToByteArray()

Published Jan 8, 2024
Contribute to Docs

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 from ByteArray via the .encodeToByteArray() and .decodeFromByteArray() methods. An example of BinaryFormat is ProtoBuf.

Example

The below code demonstrates the use of .encodeToByteArray():

import kotlinx.serialization.*
import kotlinx.serialization.protobuf.ProtoBuf
@Serializable
data 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

All contributors

Looking to contribute?

Learn Kotlin on Codecademy