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 elements1, 2, 3, 4, 5
. - We use the
toByteArray()
function onlist
to convert it to aByteArray
. - We then print the converted
ByteArray
usingjoinToString()
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.