Kotlin Set toUByteArray()
Syntax & Examples


Set.toUByteArray() extension function

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


Syntax of Set.toUByteArray()

The syntax of Set.toUByteArray() extension function is:

fun Collection<UByte>.toUByteArray(): UByteArray

This toUByteArray() extension function of Set returns an array of UByte containing all of the elements of this collection.

Return Type

Set.toUByteArray() returns value of type UByteArray.



✐ Examples

1 Converting a set of UByte values to a UByteArray

Using toUByteArray() to convert a set of UByte values to a UByteArray.

For example,

  1. Create a set of UByte values.
  2. Use toUByteArray() to convert the set to a UByteArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val ubyteSet = setOf<UByte>(1u, 2u, 3u)
    val ubyteArray = ubyteSet.toUByteArray()
    println(ubyteArray.joinToString())
}

Output

1, 2, 3

2 Handling an empty set of UByte values

Using toUByteArray() to handle an empty set of UByte values.

For example,

  1. Create an empty set of UByte values.
  2. Use toUByteArray() to convert the empty set to a UByteArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val emptySet = emptySet<UByte>()
    val ubyteArray = emptySet.toUByteArray()
    println(ubyteArray.joinToString())
}

Output


3 Converting a set of mixed UByte values to a UByteArray

Using toUByteArray() to convert a set of mixed UByte values to a UByteArray.

For example,

  1. Create a set of mixed UByte values.
  2. Use toUByteArray() to convert the set to a UByteArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val mixedSet = setOf<UByte>(1u, 255u, 128u)
    val ubyteArray = mixedSet.toUByteArray()
    println(ubyteArray.joinToString())
}

Output

1, 255, 128

Summary

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