The toByteArray() extension function in Kotlin returns an array of Byte containing all of the elements of the collection.
The syntax of Set.toByteArray() extension function is:
fun Collection<Byte>.toByteArray(): ByteArray
This toByteArray() extension function of Set returns an array of Byte containing all of the elements of this collection.
Set.toByteArray() returns value of type ByteArray
.
Using toByteArray() to convert a set of Byte values to a ByteArray.
For example,
fun main() {
val byteSet = setOf<Byte>(1, 2, 3)
val byteArray = byteSet.toByteArray()
println(byteArray.joinToString())
}
1, 2, 3
Using toByteArray() to handle an empty set of Byte values.
For example,
fun main() {
val emptySet = emptySet<Byte>()
val byteArray = emptySet.toByteArray()
println(byteArray.joinToString())
}
Using toByteArray() to convert a set of mixed Byte values to a ByteArray.
For example,
fun main() {
val mixedSet = setOf<Byte>(1, -1, 127, -128)
val byteArray = mixedSet.toByteArray()
println(byteArray.joinToString())
}
1, -1, 127, -128
In this Kotlin tutorial, we learned about toByteArray() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.