Kotlin .encodeToByteArray()

mozesi's avatar
Published Jan 8, 2024

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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
    • Beginner Friendly.
      9 hours

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

Learn Kotlin on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
    • Beginner Friendly.
      9 hours