Kotlin .decodeFromByteArray()
Published Dec 27, 2023
Contribute to Docs
The .decodeFromByteArray() method is a part of the kotlinx.serialization library and is used to deserialize/decode (convert) a byte array into a Kotlin object. Commonly used when data in a byte array format is transmitted and needs to be reverted into a Kotlin object.
Syntax
fun <T> BinaryFormat.decodeFromByteArray(ByteArray)
<T>: The type of the object to be deserializedBinaryFormat: An interface inkotlinx.serializationlibrary that provides methods for serializing and deserializing Kotlin objects in binary formats. An example ofBinaryFormatisProtoBuf, it serializes and deserializes Kotlin objects.ByteArray: The byte array containing the binary representation of the serialized object.
Example
The following example demonstrates how to use .decodeFromByteArray:
import kotlinx.serialization.*@Serializabledata class Person(val name: String, val age: Int)fun main() {val person = Person("Alice", 25)val personToByteArray = ProtoBuf.encodeToByteArray(person)val deserializedPerson = ProtoBuf.decodeFromByteArray(personToByteArray)println("Original Person: $person")println("Deserialized Person: $deserializedPerson")}
The output of the example above is:
Original Person: Person(name=Alice, age=25)Deserialized Person: Person(name=Alice, age=25)
Contribute to Docs
- 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.
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