Kotlin List toByteArray()
Syntax & Examples


Syntax of List.toByteArray()

The syntax of List.toByteArray() extension function is:

fun Collection<Byte>.toByteArray(): ByteArray

This toByteArray() extension function of List returns an array of Byte containing all of the elements of this collection.



✐ Example

1 Example

In this example,

  • We create a list of integers named list with elements 1, 2, 3, 4, 5.
  • We use the toByteArray() function on list to convert it to a ByteArray.
  • We then print the converted ByteArray using joinToString() to display its elements separated by commas.

Kotlin Program

fun main(args: Array<String>) {
    val list: List<Int> = listOf(0x7A, 0x41, 0x07)
    val byteList = list.map { it.toByte() }
    val byteArray = byteList.toByteArray()
    println(byteArray.joinToString())
}

Output

122, 65, 7

Summary

In this Kotlin tutorial, we learned about toByteArray() extension function of List: the syntax and few working examples with output and detailed explanation for each example.