Kotlin Set toByteArray()
Syntax & Examples


Set.toByteArray() extension function

The toByteArray() extension function in Kotlin returns an array of Byte containing all of the elements of the collection.


Syntax of Set.toByteArray()

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.

Return Type

Set.toByteArray() returns value of type ByteArray.



✐ Examples

1 Converting a set of Byte values to a ByteArray

Using toByteArray() to convert a set of Byte values to a ByteArray.

For example,

  1. Create a set of Byte values.
  2. Use toByteArray() to convert the set to a ByteArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val byteSet = setOf<Byte>(1, 2, 3)
    val byteArray = byteSet.toByteArray()
    println(byteArray.joinToString())
}

Output

1, 2, 3

2 Handling an empty set of Byte values

Using toByteArray() to handle an empty set of Byte values.

For example,

  1. Create an empty set of Byte values.
  2. Use toByteArray() to convert the empty set to a ByteArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val emptySet = emptySet<Byte>()
    val byteArray = emptySet.toByteArray()
    println(byteArray.joinToString())
}

Output


3 Converting a set of mixed Byte values to a ByteArray

Using toByteArray() to convert a set of mixed Byte values to a ByteArray.

For example,

  1. Create a set of mixed Byte values.
  2. Use toByteArray() to convert the set to a ByteArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val mixedSet = setOf<Byte>(1, -1, 127, -128)
    val byteArray = mixedSet.toByteArray()
    println(byteArray.joinToString())
}

Output

1, -1, 127, -128

Summary

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.