Kotlin Array.toByteArray() Tutorial
The Array.toByteArray()
function in Kotlin is used to convert an Array
of Byte
type values, into a ByteArray
. It creates a new ByteArray
containing the elements of the original array.
This is just a conversion of data from Array<Byte>
type to ByteArray
type.
This tutorial will explore the syntax of the Array.toByteArray()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.toByteArray()
function is as follows:
fun Array<out Byte>.toByteArray(): ByteArray
Examples for Array.toByteArray() function
1. Convert Array of bytes to ByteArray
In this example, we’ll take an array of bytes, and convert this Array into a ByteArray
using Array.toByteArray()
.
Kotlin Program
fun main() {
val originalArray: Array<Byte> = arrayOf(65, 66, 67, 68, 69)
// Using toByteArray() to convert the Array of bytes to a ByteArray
val byteArray = originalArray.toByteArray()
// Printing the original array and the resulting byte array
println("Given Array:\n${originalArray.contentToString()}\n")
println("Byte Array:\n${byteArray.contentToString()}")
}
Output
Given Array:
[65, 66, 67, 68, 69]
Byte Array:
[65, 66, 67, 68, 69]
Summary
In this tutorial, we’ve covered the Array.toByteArray()
function in Kotlin, its syntax, and how to use it to convert an Array of Byte
values into a ByteArray
. This function is particularly useful when dealing with data serialization or network communication where byte arrays are commonly used.