Kotlin Set toUShortArray()
Syntax & Examples


Set.toUShortArray() extension function

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


Syntax of Set.toUShortArray()

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

fun Collection<UShort>.toUShortArray(): UShortArray

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

Return Type

Set.toUShortArray() returns value of type UShortArray.



✐ Examples

1 Converting a set of UShort values to a UShortArray

Using toUShortArray() to convert a set of UShort values to a UShortArray.

For example,

  1. Create a set of UShort values.
  2. Use toUShortArray() to convert the set to a UShortArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val ushortSet = setOf<UShort>(1u, 2u, 3u)
    val ushortArray = ushortSet.toUShortArray()
    println(ushortArray.joinToString())
}

Output

1, 2, 3

2 Handling an empty set of UShort values

Using toUShortArray() to handle an empty set of UShort values.

For example,

  1. Create an empty set of UShort values.
  2. Use toUShortArray() to convert the empty set to a UShortArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val emptySet = emptySet<UShort>()
    val ushortArray = emptySet.toUShortArray()
    println(ushortArray.joinToString())
}

Output


3 Converting a set of mixed UShort values to a UShortArray

Using toUShortArray() to convert a set of mixed UShort values to a UShortArray.

For example,

  1. Create a set of mixed UShort values.
  2. Use toUShortArray() to convert the set to a UShortArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val mixedSet = setOf<UShort>(1u, 65535u, 128u)
    val ushortArray = mixedSet.toUShortArray()
    println(ushortArray.joinToString())
}

Output

1, 65535, 128

Summary

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