Kotlin .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 fromByteArrayvia the.encodeToByteArray()and.decodeFromByteArray()methods. An example ofBinaryFormatisProtoBuf.
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
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